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.
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.
Downstream analytics show an unexpected spike in daily active users for yesterday. Outline a detailed root-cause-analysis plan to determine whether this is a genuine product change, an analytics query bug, an ETL data-quality issue, or a reporting or dashboard problem. Include specific checks and queries, sampling approaches, time-window comparisons, and how you would use deploy history and feature flags, and how you would escalate findings to product and data-science stakeholders.
Sample Answer
Direct answer
A DAU spike has four structurally different possible causes: a genuine product change (a launch, a viral moment, a marketing push), an analytics query bug (a change to the DAU query/definition itself), an ETL data-quality issue (duplicate ingestion, a join fan-out), or a reporting/dashboard bug (a caching issue, a timezone/date-boundary bug). Each has a distinct signature in the underlying data, so the investigation should check for each signature specifically rather than guessing.
Structured elaboration
- Check for a genuine product cause first, since it's the easiest to confirm or rule out: was there a launch, a marketing campaign, a notification blast, or any known external event on the spike date? Cross-check against a deploy/release calendar and marketing calendar before assuming the data itself is wrong.
- Check for duplicate counting (an ETL data-quality issue). Query the RAW event/user table directly and check whether the count of DISTINCT user IDs actually grew, versus the count of raw EVENTS growing while distinct users did not; if the underlying user IDs look normal but rows exploded, suspect a fan-out from a recent join change or a re-processing/backfill that accidentally double-inserted a batch of events.
- Sample and manually inspect a subset of the records driving the spike. Pull a random sample of, say, 50 to 100 of the "new" or spike-contributing user IDs (or events) and check by hand whether they look like genuine distinct users (plausible account age, a believable mix of actions) versus synthetic, duplicated, or bot-like records (near-identical timestamps, sequential or obviously-generated-looking IDs, a single action type repeated with no other activity). This catches a category the aggregate distinct-count check alone can miss: a bot wave or a load-test script that creates real-looking, genuinely-distinct user IDs that still are not real active users.
- Check for an analytics query bug. Diff the DAU query's current definition against a known-good historical version (via version control or a query-history feature); a changed filter, a changed date-boundary calculation, or an accidentally removed deduplication step in the query itself would inflate the count without any change to the underlying data at all.
- Check for a reporting/dashboard bug specifically. Query the underlying data source directly, bypassing the dashboard/BI tool entirely, and compare that number to what the dashboard shows; a mismatch between the two, where the raw query gives a normal number but the dashboard shows the spike, isolates the bug to the dashboard/caching layer rather than the data or the query logic.
- Time-window comparisons, useful across several of the above: compare the spike day's hourly pattern against a typical day's; a spike concentrated in one unusual hour (rather than spread proportionally across the day like organic traffic) points toward a batch-processing artifact (a backfill or reprocessing job that ran during that hour) rather than organic user behavior, which is normally smoother.
- Use deploy history and feature flags to check for anything that shipped around the spike's start time, on either the product side (a change to what counts as a session/active user) or the data-pipeline side (a change to the ingestion or transformation logic).
Worked example
Checking distinct user IDs directly against the raw event table shows the actual count of distinct users is normal; the spike is entirely in raw event volume. That immediately rules out (1) genuine product growth and narrows to (2), (3), or (4). Checking the DAU query definition shows no recent changes, ruling out (2). Checking the dashboard against a direct raw query shows they now AGREE (both show the spike), ruling out a pure dashboard-layer bug (4) and pointing squarely at (3): the underlying pipeline. Investigating the ingestion job's recent history shows a backfill job re-ran for a date range that overlapped the spike day due to a scheduling misconfiguration, double-counting a subset of events. Checking distinct users again more carefully (specifically, checking for exact-duplicate event rows rather than just aggregate distinct-user count, since a backfill duplicate for an ALREADY-active user wouldn't move the distinct-user count but would inflate any event-count-based metric) confirms duplicate rows matching the backfill's re-run window exactly.
Escalating findings: present product and data-science stakeholders with the specific mechanism (a backfill re-run, not a genuine trend) and the exact affected window, so they don't act on a false signal (staffing up for sustained growth that isn't real, or reporting an inflated number externally), and file the scheduling gap that allowed the double-run as the concrete process fix, not just a one-time data correction.
Trade-offs and pitfalls
The trap is anchoring on the first plausible story (often the "genuine growth" explanation, since it's the most pleasant one to report) without checking the data for the specific signature that would confirm or rule it out; each of the four candidate causes has a checkable, distinguishing signature, and working through them in order is faster and more reliable than guessing based on which explanation feels most likely.
An upstream service emits events with out-of-order timestamps, causing incorrect downstream aggregations, and the same class of issue has broken a streaming ingestion pipeline's aggregations before. Describe methods to detect out-of-order events, the windowing strategies you would use to handle event-time processing including watermarking and allowed lateness, and how you would design transformations to be robust to reordering and late arrivals. Separately, describe the immediate mitigations you would apply while a fix is in flight, and the diagnostic steps and long-term design changes, such as buffering or idempotency, you would implement afterward.
Sample Answer
Direct answer
Detecting out-of-order events means comparing each event's OWN timestamp (event time) against the order it actually arrived in (processing time), and handling them robustly means designing the aggregation logic to tolerate a bounded amount of lateness via watermarking rather than assuming arrival order matches event order. Separately, when out-of-order arrival has already broken downstream aggregations in production, the response splits into an immediate mitigation and a long-term design fix.
Structured elaboration
Detecting out-of-order events: track, per event source or partition, the maximum event-time timestamp seen SO FAR; any newly arriving event whose timestamp is earlier than that running maximum (minus some small, expected jitter tolerance) is out of order. This is cheap to compute as a running comparison and doesn't require buffering to detect, only to CORRECT for.
Windowing strategies for event-time processing:
- Watermarking: the processing engine tracks an estimate of "how far behind can we assume events have arrived by now," advancing as time passes; a window is finalized once the watermark passes its end boundary, giving late-but-within-tolerance events a chance to be included before the window closes.
- Allowed lateness: an explicit, bounded grace period after a window's watermark-triggered close during which further late events are still accepted and merged into an already-emitted (but revisable) result, rather than silently dropped; the width of this tolerance is a direct trade-off between correctness (fewer legitimately-late events dropped) and result latency (how long you wait before considering a window "final").
- Choosing tolerances: based on the OBSERVED lateness distribution of the actual upstream source (measure it, don't guess), setting the allowed-lateness window wide enough to capture the large majority of legitimately late events without indefinitely delaying every window waiting for a rare, extreme outlier.
Designing transformations to be robust to reordering: use event-time (not processing-time) as the basis for all windowing and aggregation logic; make aggregation operations idempotent/commutative where possible (a sum or count naturally tolerates late arrival if the window is still open or within its lateness tolerance, simply incrementing the existing partial result); and explicitly define and monitor a dropped-events metric for anything arriving PAST the allowed-lateness window, so silently-dropped late data is at least visible and quantified rather than invisible.
Immediate mitigations while investigating an active incident: widen the allowed-lateness window temporarily if the current lateness distribution has shifted wider than the configured tolerance (a quick, reversible change); if a specific upstream source is confirmed to be the origin of unusually late events, consider a temporary buffering/reordering stage specifically for that source before it enters the main aggregation pipeline, isolating the fix to where it's needed rather than loosening tolerance globally.
Diagnostic steps and long-term design changes: confirm WHY the upstream source is emitting out-of-order events in the first place (a multi-producer system with no synchronized clock or sequencing, a retry that re-emits an event with its original timestamp after a delay, a partition rebalance causing reordering) since the long-term fix differs depending on the mechanism: a synchronized/monotonic sequence number from the source (if achievable) can eliminate ambiguity entirely; a redesigned watermarking strategy (per-partition rather than global, if the lateness pattern differs meaningfully by partition) can better match the actual data's behavior; and buffering with an explicit, monitored reordering stage is the right fix when the source's out-of-order behavior is a known, bounded, and unavoidable characteristic rather than a bug to fix at the source.
Worked example
An upstream service occasionally retries a failed publish, re-emitting an event with its ORIGINAL event-time timestamp well after the window it belongs to has already closed and been finalized downstream, because the retry logic (correctly) preserves the original timestamp rather than using retry-time. Immediate mitigation: widen the allowed-lateness window to comfortably cover the observed retry-delay distribution, measured from the retry mechanism's own logs. Long-term: add explicit monitoring for events arriving past the lateness window (quantifying how much is actually being dropped, which turns out to be a small, bounded, and now-understood amount from this specific retry pattern) and document the trade-off explicitly rather than continuing to silently drop them with the tolerance too tight.
Trade-offs and pitfalls
Widening the allowed-lateness window indefinitely to catch every possible late event trades away result LATENCY (windows take longer to finalize) for completeness, which isn't free; the right tolerance is set from the actual, measured lateness distribution of the specific source, not a defensively-large guess, and should be revisited if the upstream source's behavior changes.
A streaming pipeline using a message queue such as Kafka shows one consumer partition's lag steadily increasing while the others stay healthy. Describe a methodical debugging approach, stating which metrics and logs you would inspect such as broker metrics, consumer offsets, garbage collection, and network, the possible causes such as data skew, hot keys, or consumer-side processing, and the remediation options with their trade-offs.
Sample Answer
Direct answer
One partition's lag climbing while others stay healthy means that specific partition's consumer is falling behind its own producer rate, and since Kafka guarantees ordering only WITHIN a partition, this is almost always localized to something specific about that partition's data or its assigned consumer, not a cluster-wide issue (which would show up across all partitions). The methodical approach checks broker-side health for that partition, then consumer-side processing time for messages from it, then the data itself for skew or hot keys.
Structured elaboration
- Check the raw consumer-offset numbers behind the lag figure itself, before looking anywhere else. Pull the partition's committed offset alongside its log-end-offset (the newest offset available to consume) over time: if log-end-offset is climbing fast (the partition is genuinely receiving more messages) while the committed offset climbs more slowly, that's a real processing-can't-keep-up-with-produce-rate problem. If instead the committed offset has essentially STOPPED advancing while log-end-offset keeps climbing, that points at a stuck, crashed, or endlessly-retrying consumer instance for that partition specifically, or one that's processing but failing to commit, which is a meaningfully different problem (and fix) than a consumer that's simply behind.
- Check broker-side metrics for that specific partition next, to rule out a broker/replica issue: under-replicated partition status, leader election history (a recent leader change can cause a temporary processing pause), and per-partition produce/fetch request latency, isolated to that partition's leader broker specifically.
- Check consumer-side processing time for messages from that partition specifically, not aggregate consumer metrics: if the SAME consumer process also handles other, healthy partitions, per-partition processing-time breakdown (if available) shows whether messages from the lagging partition are taking longer to process individually, pointing at a data-content or downstream-dependency issue tied to that partition's messages rather than a consumer-wide problem.
- Check for a hot key or data skew causing that partition to simply carry disproportionately more or more-expensive-to-process messages: if partitioning is by a key (customer ID, event type) and one key's traffic has grown, a partition happens to receive that key's outsized share of messages, and no amount of consumer tuning fixes an inherently uneven partition assignment.
- Check garbage collection specifically on the consumer process handling that partition, since GC pauses can look exactly like "this partition is slow" if the pausing consumer happens to be the one assigned to it, especially in a consumer group where partition-to-consumer assignment isn't perfectly even.
- Check network path health between that specific broker (the partition's leader) and the consumer, since a per-broker network issue (not visible in aggregate cluster network metrics) would manifest as exactly this localized symptom.
Possible causes, matched to their diagnostic signature:
- Data skew / hot key: confirmed by checking per-partition message rate and average message size; a partition receiving disproportionately more or larger messages explains slower per-partition throughput without any bug at all, just an uneven partitioning scheme.
- Consumer-side processing bottleneck: confirmed by per-partition processing-time metrics showing this partition's messages specifically take longer to process, pointing at message CONTENT (a specific event type requiring more expensive downstream calls) rather than infrastructure.
- Broker/replica issue: confirmed by broker-side metrics for that specific partition showing under-replication, frequent leader elections, or elevated fetch latency isolated to that partition's broker.
Remediation options and their trade-offs:
- Re-partitioning with a better key (spreading the hot key's traffic across more partitions, e.g., via a composite or salted key) fixes data skew at the source but requires a migration and, depending on ordering guarantees needed, may not be trivial if downstream consumers rely on the current per-key ordering.
- Scaling consumer parallelism (adding more partitions and consumers) helps if the bottleneck is aggregate throughput, but does NOT help a single hot-key partition, since Kafka can't split one partition's messages across multiple consumers within the same consumer group; the hot partition remains a ceiling regardless of how many idle consumers exist for OTHER partitions.
- Optimizing the specific slow processing path (if the bottleneck is consumer-side processing time for that partition's message content) directly addresses the root cause without needing any partitioning change, and is the right fix when the skew is in processing COST rather than message VOLUME.
Worked example
Per-partition message-rate metrics show the lagging partition receives roughly 3x the message volume of its peers, tracing to a specific high-traffic customer whose events all hash to that one partition under the current keying scheme. Per-partition processing time is otherwise normal (ruling out a consumer-side cost issue), and broker metrics for that partition are healthy (ruling out a broker issue). The remediation: introduce a composite partition key (customer ID plus a bounded random suffix) that spreads this one customer's traffic across several partitions instead of concentrating it on one, while preserving per-sub-key ordering for any downstream logic that needs it, resolving the lag by addressing the actual data-skew cause rather than just adding more consumer capacity that a single hot partition couldn't use anyway.
Design an experiment to test the hypothesis that increased job runtimes are caused by cloud network egress throttling during scheduled backups. Specify the metrics and logs you would collect, your control and treatment groups, how you would inject synthetic load or failover backups, and the statistical analysis you would apply to validate or refute the hypothesis.
Sample Answer
Direct answer
Design a controlled experiment that isolates network egress specifically from the other plausible causes of longer job runtimes: run the same backup workload with egress-heavy traffic artificially suppressed or shifted to an off-peak window (the treatment), compare its runtime against the normal, unmodified schedule (the control), and use network-level metrics (not just job duration) as the primary evidence, since job duration alone can't distinguish egress throttling from several other causes that would look identical from the outside.
Structured elaboration
- Define the hypothesis precisely and what would falsify it. "Increased job runtimes are caused by network egress throttling during scheduled backups" implies a specific, testable prediction: runtimes should correlate with WHEN backups run (not with data volume, not with unrelated cluster load), and network-level metrics (egress bytes/sec, any provider-reported throttling signal) should show a ceiling being hit specifically during the slow windows.
- Metrics and logs to collect: job start/end timestamps and duration; network egress throughput for the job's traffic specifically (not aggregate host traffic, which could hide the effect); cloud-provider throttling indicators if the platform exposes them (some providers report throttled-bytes or return specific response codes/headers when a bandwidth cap is hit); backup job schedule and duration, to know exactly which windows are "backup active" versus not.
- Control and treatment groups: control = runs of the job during normal backup-schedule conditions (the current, unmodified state); treatment = runs of the SAME job, ideally on the same day-of-week/data-volume profile, either scheduled to avoid overlapping with backups, or with backup traffic artificially shifted/throttled down for the test window, isolating the one variable (backup-induced egress contention) being tested.
- Injecting synthetic load or failing over backups, as an alternative/complementary experiment: if you can't cleanly separate the job's natural schedule from backups, inject SYNTHETIC egress load mimicking the backup's traffic pattern during an otherwise backup-free window and see if the job slows down anyway; if it does, that's strong evidence for the egress-contention hypothesis independent of whatever else backups might be doing (like CPU contention on a shared host).
- Statistical analysis to apply: run enough repetitions of both control and treatment conditions to account for natural run-to-run variance (a single run of each is not enough to distinguish a real effect from noise); compare the distributions (not just single-run averages) using a standard two-sample test appropriate for the sample size and distribution shape: a t-test (checks whether two averages differ more than random run-to-run noise would explain, assuming a roughly bell-curve-shaped distribution) if the runtime distribution is roughly normal and sample sizes are reasonable, or a non-parametric test like Mann-Whitney U (the same kind of check, but without assuming a bell-curve shape, useful when the data is skewed or the sample is small) if it's skewed or sample sizes are small. Report the effect size (how BIG the difference actually is, not just whether one exists) and confidence interval (a range that's likely to contain the true difference, given the noise in the measurement), not just whether the difference is "significant," since a statistically real but tiny effect might not be the operationally dominant cause.
Worked example
Running the job for two weeks under normal conditions (control, overlapping backups on schedule) and two weeks with backups shifted to a non-overlapping window (treatment): control-condition runtimes average 90 minutes with high variance specifically on backup days; treatment-condition runtimes average 55 minutes with much lower variance across all days. A Mann-Whitney U test on the two runtime distributions shows the difference is unlikely to be due to chance, and network egress metrics for the job's own traffic show a clear ceiling being hit specifically during the control condition's backup-overlap windows, directly corroborating the mechanism, not just the correlation. Combined, this supports the hypothesis with both a statistical result and a direct mechanistic signal (the throttling ceiling itself), which is stronger evidence than either alone.
Trade-offs and pitfalls
Job duration alone, without the network-level corroborating metric, is weak evidence: several other causes (unrelated cluster CPU contention during the same backup window, a coincidental data-volume pattern that happens to align with the backup schedule) could produce the same duration pattern. The experiment design specifically avoids this by collecting network-throughput evidence that would DISTINGUISH the egress-throttling hypothesis from those alternatives, rather than relying on timing correlation alone.
Unlock Full Question Bank
Get access to all 47 Debugging and Systematic Troubleshooting interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.