Production Incident Diagnosis and Distributed Systems Troubleshooting Questions
Debugging distributed systems under fire: diagnosing latency and reliability regressions, root-causing across service boundaries, reading traces and metrics during an incident, and reasoning about complex production failures. Covers the investigative method for hard-to-reproduce, multi-service problems. The operational counterpart to resilient design.
A Kafka consumer group's lag is steadily increasing for a topic, and you've been paged because the aggregation pipeline it feeds is now hours behind. Describe a structured troubleshooting approach: which metrics (consumer throughput, processing time, rebalance frequency) and logs you'd inspect, how you'd determine whether the producer, the broker, or the consumer is the bottleneck, and the short-term and long-term remediations (parallelism, partitioning, backpressure) you'd apply.
Sample Answer
Direct answer. Rising consumer lag on its own only tells you the consumer group is falling behind the producers; the diagnostic work is figuring out which of producer, broker, or consumer is actually the bottleneck, because each implies a different fix.
Structured elaboration.
- Check whether the problem is per-partition or across the whole group. If lag is climbing on every partition roughly equally, that points to the consumer group as a whole being under-provisioned relative to total throughput. If lag is climbing on ONE partition while others are fine, that points to a hot key (one specific key receiving far more traffic than others, so every message for it lands on the same partition and overloads it) or uneven partitioning, or a single consumer instance stuck on that partition.
- Compare producer throughput against consumer throughput directly. If the producer's messages-per-second has genuinely grown (a real traffic increase) and consumer throughput hasn't kept pace, that's a capacity problem: the fix is adding consumer parallelism, not debugging a bug. If producer throughput is flat but consumer throughput has DROPPED, something changed on the consumer side.
- If it's the consumer side, check processing time per message and rebalance frequency. A rising per-message processing time (from a slow downstream call the consumer makes, a memory leak, or a change in message size or shape) directly slows consumption. Frequent consumer-group rebalances are a distinct and common cause: if consumers are being kicked out and rejoining repeatedly (often because processing a batch takes longer than the configured
max.poll.interval.ms), the group spends real time NOT consuming while it rebalances, which shows up as growing lag even if per-message processing hasn't changed. - If producer or broker side, check broker health and network. Broker-side saturation (disk I/O, network throughput) can slow how fast the consumer can even fetch records, independent of how fast it processes them; this shows up as slow fetch requests rather than slow processing.
- Remediate. Short-term: increase consumer parallelism (more instances or more partitions, if there's room), or shed non-critical processing to catch up faster. Long-term: fix the root slowdown found in the previous steps, and consider decoupling slow downstream calls (like a blocking write to another system) out of the hot consume path via backpressure or a queue.
Worked example. Suppose the consumer group has 10 partitions and 10 consumer instances, and lag is climbing evenly across all 10 rather than concentrated on one. Producer throughput has grown from roughly 2,000 to 3,500 messages per second over the past week (a genuine 75% increase from a new event source), while each consumer instance's processing rate has stayed flat at about 220 messages per second, for a group capacity of 2,200 messages per second, just short of the new 3,500 msg/sec producer rate. That's a straightforward capacity gap, not a bug: adding roughly 6 more consumer instances (and a matching increase in partitions, since you can't have more active consumers than partitions in a group) would bring group capacity to about 3,520 msg/sec, back above the current producer rate.
Trade-offs and pitfalls. It's easy to assume lag always means 'add more consumers', but if the real cause is frequent rebalances or a slow per-message downstream call, adding consumers without fixing that root cause either doesn't help or helps only briefly before the same problem recurs at a slightly higher throughput. Also watch for the case where you CAN'T add more consumers because you're already at the partition count; in that case the fix has to be increasing partitions (which requires care, since it changes key-to-partition assignment) or reducing per-message processing time instead.
A distributed job-processing system suffers cascading failures under peak load. Create a diagnostic approach to find the bottleneck (queuing, thread pools, garbage collection, or downstream latency), then propose immediate mitigations (rate-limiting, load shedding, backpressure) and longer-term architectural fixes (partitioning, horizontal scaling, async decoupling). Discuss the trade-offs of each.
Sample Answer
Direct answer. In a distributed job-processing system under peak load, cascading failure usually starts at ONE bottleneck (queuing, thread pools, GC, or a slow downstream) and spreads because upstream stages keep pushing work at a rate the bottlenecked stage can no longer absorb, so the diagnostic job is finding that first bottleneck before the whole system look uniformly unhealthy.
Structured elaboration.
- Find where work is actually piling up, not just where things look broken. Check queue depths (or backlog size) at each stage of the pipeline; the stage with a rapidly growing queue, while stages before it look normal, is usually the actual bottleneck, and stages AFTER it may look artificially healthy simply because they're starved of work, not because they're fine.
- For the identified bottleneck stage, check the specific resource. Thread-pool saturation shows as a growing count of queued tasks with active threads pinned at the pool's max; GC pressure shows as pause time and frequency correlating with the slowdown; downstream latency shows as the stage's own outbound calls taking longer than normal.
- Distinguish 'genuinely more work than capacity' from 'a specific slow operation'. If EVERY unit of work through the bottleneck stage got proportionally slower, suspect a shared resource under contention (GC, a lock, a saturated connection pool). If most work is fine but a subset is disproportionately slow, suspect a specific bad input or a specific downstream call that only some jobs make.
- Immediate mitigations, matched to what you find. Rate-limiting or shedding load at the entry point buys time without fixing the root cause but prevents things from getting worse while you investigate. Backpressure (having upstream stages slow down when downstream stages are behind, rather than blindly pushing more work at them) is a more targeted immediate response that specifically prevents the pileup from cascading further upstream.
- Long-term architectural fixes. Partitioning (splitting work into independent shards so one hot partition's overload doesn't affect others), horizontal scaling of the specific bottlenecked stage, and async decoupling (using a durable queue between stages so a slow downstream stage doesn't block the upstream stage's own throughput) each address a different aspect: partitioning limits blast radius, scaling adds raw capacity, decoupling prevents a slow stage from propagating its slowness backward through the pipeline.
Worked example. Suppose queue-depth metrics show stage 3 of a 5-stage pipeline growing from a typical few hundred queued jobs to over 50,000 during peak load, while stages 1 and 2 look normal and stages 4 and 5 are nearly idle (starved, waiting on stage 3's output). Checking stage 3's thread pool shows it's pinned at its configured maximum of 20 threads, each one busy, with no GC or lock-contention anomaly. That points at simple capacity: stage 3's throughput ceiling (roughly bounded by 20 concurrent workers times their average per-job time) is below the rate work arrives at during peak load. If each job in stage 3 takes about 2 seconds, 20 threads give a ceiling of roughly 10 jobs per second; if peak load is pushing closer to 25 jobs per second into stage 3, that 2.5x gap explains the queue growing without bound during the peak window. The mitigation is either raising stage 3's concurrency (if the underlying resource, likely a downstream call or database, can handle more concurrent load) or partitioning stage 3's work so multiple independent worker pools each handle a slice, rather than one pool being the single ceiling for all traffic.
Trade-offs and pitfalls. Backpressure and rate-limiting both trade a clean failure (rejecting or delaying some work explicitly) for the alternative of an uncontrolled pileup that eventually causes a messier failure (memory exhaustion from unbounded queues, or cascading timeouts); that trade is usually worth it, but stakeholders need to understand that 'load shedding' means some work is deliberately deferred or dropped, not silently absorbed. Partitioning also has a real cost: if partitioning is done on a key that's unevenly distributed (a few very active tenants, for example), you can end up with the exact same bottleneck concentrated on one partition instead of solved. Horizontal scaling has its own trade-off: it's usually the fastest lever when the bottlenecked stage is stateless and genuinely just short on capacity, but it doesn't help, and can even mask, a real algorithmic or lock-contention problem, and it costs real money to run extra capacity that's only needed at peak. Async decoupling trades a simpler, synchronous call chain for a durable queue between stages, which absorbs bursts and stops a slow downstream from blocking upstream throughput, but it adds real operational complexity (the queue itself now needs its own monitoring and capacity planning) and can turn a request that used to fail fast into one that succeeds eventually with a much longer and less predictable end-to-end latency, which is not free for every kind of job.
A critical production pipeline shows silent data loss between stages: some events go missing downstream with no obvious errors, and in one recent case the affected job had actually failed silently and kept running for two days before anyone noticed. As the on-call data engineer, provide a step-by-step incident response: your immediate mitigations, how you'd collect evidence to determine the true extent of the loss or corruption, your root-cause-analysis approach, and the long-term prevention you'd put in place (instrumentation, data contracts, reconciliation jobs).
Sample Answer
Direct answer. When data goes missing silently, with no errors and no alerts firing, the first job is not root-causing yet: it's establishing exactly how much data is affected and for how long, because that scope determines both your mitigation urgency and what a correct fix even needs to repair.
Structured elaboration.
- Establish scope before cause. Compare an authoritative count or checksum at the start of the pipeline against the same count or checksum at the end, for a range of recent time windows, to find exactly when the loss started and how much has been lost. Without this, you can't tell stakeholders how bad it is, and you risk fixing the code but missing that a specific batch or partition also needs to be reprocessed.
- Contain first, then investigate. If the pipeline is still running and still losing data, the immediate priority is stopping further loss: this might mean pausing the pipeline stage that's dropping events, or routing new events to a location where they're safe (a raw, unprocessed store) even if you haven't fixed the processing yet.
- Walk the pipeline stage by stage. With no obvious error, the loss is likely happening in a place that fails silently: a filter or transform step that drops records that don't match an expected shape without logging them, a deduplication step that's over-aggressive and treats distinct events as duplicates, an at-most-once delivery mechanism (the message is sent once and never retried, so if it's lost in transit it's simply gone, unlike at-least-once delivery which keeps retrying until acknowledged) that occasionally drops a message under backpressure (a signal from an overwhelmed downstream stage telling upstream to slow down or drop work rather than queue it indefinitely), or a downstream write that silently no-ops on a conflict instead of erroring. Check each stage's input count against its output count to localize which stage is where records disappear.
- Reconstruct the two-day case specifically. For an incident that ran silently for an extended period, check whether any monitoring existed at all for input-versus-output counts at each stage; if not, that absence of monitoring is itself part of the root cause, since a real bug that WOULD have been caught in minutes with the right check instead ran undetected for days.
- Recover and prevent recurrence. Once the losing stage is found, recovery usually means reprocessing the affected window from a raw or replayable source if one exists; if there is no way to recover the missing data, that gap needs to be communicated honestly to whoever consumes this data downstream. Prevention has three complementary parts: instrumentation (emitting an explicit count or checksum metric at every stage boundary, not just logging on error, so a silent drop shows up on a dashboard instead of requiring someone to notice); data contracts (an explicit, enforced agreement on what shape and volume of data each stage should produce, so a stage that silently changes behavior violates a checkable contract rather than drifting unnoticed); and scheduled reconciliation jobs that periodically re-verify end-to-end counts independently of the pipeline's own reporting, catching a class of bug where the pipeline's own instrumentation is itself the thing that's wrong.
Worked example. Say a checksum comparison finds the pipeline's ingestion stage received 100,000 events per hour throughout the affected window, but a stage-by-stage count shows only 94,000 events per hour reaching the final sink, a stable roughly 6% loss rather than a spike. Checking each intermediate stage's input-versus-output count in turn shows the drop happens entirely at a deduplication step, whose input and output counts differ by exactly the missing 6%. Looking at that step's logic reveals it dedupes on a composite key that, for a specific event type, isn't actually unique across different real events, so it's discarding legitimate events it mistakes for duplicates. Because the loss was steady rather than a sudden failure, it evaded any anomaly-style alerting that watches for sudden drops, which is exactly why an ongoing count-reconciliation check (rather than only alerting on sudden changes) is the prevention that would have caught it on day one instead of day two.
Trade-offs and pitfalls. The biggest pitfall is jumping straight to a fix before establishing scope: without the before/after counts, you don't know if you're looking at a total outage of one stage or a steady small leak, and those need very different urgency and different recovery plans. The other common mistake is fixing the code bug and declaring victory without checking whether the ALREADY-LOST data during the incident window can be recovered or backfilled from a raw source; a correct fix going forward doesn't repair the historical gap on its own.
A customer reports periodic data corruption in a distributed SQL database used by multiple teams. During your investigation you have access to the schema, the replication topology, and recent query patterns. Explain a structured root-cause-analysis approach: which metrics, tests, and experiments you would run, and how you would isolate the contributing factors from each other.
Sample Answer
Direct answer. Periodic, hard-to-pin-down corruption in a multi-team shared database calls for isolating contributing factors systematically, since 'periodic' suggests a trigger condition rather than a constant bug, and 'multiple teams' means the cause could originate from any of several independent write paths.
Structured elaboration.
- Characterize the corruption precisely first. What exactly is wrong: are values incorrect, are rows missing or duplicated, are relationships between tables violated? The SHAPE of the corruption narrows the search dramatically; a duplicated-row pattern points toward replication or retry logic, while an incorrect-value pattern points more toward application logic or a race condition in a read-modify-write sequence.
- Look for periodicity in the corruption itself, not just assume it's random: does it correlate with a specific time of day, a specific batch job, a specific team's deploy schedule, or a specific load pattern? A pattern that recurs at the same time daily strongly suggests a scheduled job as the trigger, versus a pattern tied to load suggesting a race condition that only manifests under concurrency.
- Check the replication topology for a role in the mechanism, since it was explicitly available: if corruption appears differently on different replicas, or specifically on read replicas but not the primary (or vice versa), that points at a replication-specific bug (a replication lag interacting with an application's read-then-write logic, for example) rather than a bug that would corrupt the primary directly.
- Correlate against recent query patterns from EACH team, since multiple teams write to this database: look for any team's queries that involve a read-modify-write sequence without proper locking or optimistic-concurrency checks, since that's a classic source of intermittent corruption that only manifests when two writes race closely enough in time, which explains both the periodicity (needs a specific timing collision) and the multi-team angle (any team's racy write pattern is a candidate).
- Design experiments to confirm, not just infer. Once you have a specific hypothesis (say, team B's batch job races with team A's real-time writes during a specific window), a targeted test that deliberately reproduces that timing collision in a non-production environment can confirm the mechanism definitively before you commit to a fix.
Worked example. Suppose the corruption pattern is specifically duplicate rows with slightly different values in a subset of fields, and it correlates closely with a nightly batch job's run window. Investigating that batch job's logic shows it reads a row, computes an update based on current state, and writes it back, all without an optimistic-concurrency check (no version column comparison) or a row-level lock; if a real-time write from the application happens to land in the narrow window between the batch job's read and its write, the batch job's write can silently overwrite the real-time write's change based on now-stale data it read moments earlier, and depending on the exact field overlap, this can look like a duplicate or a partially-reverted row. The fix is adding an optimistic-concurrency check (reject the batch job's write if the row has changed since it was read, and retry the read-modify-write cycle) or moving the batch update to use an atomic, single-statement update rather than a separate read-then-write, either of which removes the race window entirely.
Trade-offs and pitfalls. It's easy to blame 'the database' or 'replication' generically when the actual root cause is an application-level race condition in how one specific job reads and writes data; walking through each team's actual query PATTERNS, not just infrastructure-level metrics, is often what actually finds this class of bug. It's also worth checking whether the SAME read-modify-write-without-locking pattern exists in other jobs or services touching this database, since a fix that only patches the one job found here leaves the same latent bug available to reappear from a different write path.
During a migration, an analytics service starts receiving inconsistent data because two different teams are using slightly different versions of an event schema. Outline a concrete plan to detect this kind of schema divergence in production, enforce schema compatibility going forward, and backfill or reconcile the historical inconsistencies it already caused.
Sample Answer
Direct answer. Schema divergence between teams is fundamentally a coordination failure showing up as a data problem, so the fix needs both a technical detection mechanism and an actual compatibility CONTRACT that both teams agree to and can't silently drift away from again.
Structured elaboration.
- Detect the divergence precisely first. Compare the two teams' actual event schemas field by field: which fields exist in one but not the other, which fields exist in both but with different types or semantics (the more dangerous case, since it doesn't fail loudly, it just silently produces wrong values), and since when the two schemas diverged, by checking version history or deploy timestamps for each team's event-producing code.
- Enforce schema compatibility going forward. A schema registry (a central, versioned definition of the event shape that both teams' producers validate against before publishing) is the standard mechanism: it rejects or flags an incompatible change at publish time rather than letting it silently ship and diverge. Compatibility rules (for example, requiring new fields to be optional with sane defaults, and disallowing changing an existing field's type) need to be explicit and enforced automatically, not just documented and hoped for.
- Backfill or reconcile historical inconsistencies. For data already affected by the divergence, decide per-field whether it can be safely reconciled (if one team's version is clearly authoritative or a mapping between the two versions is well-defined) or whether the affected historical range needs to be flagged as lower-confidence rather than silently 'fixed' with a guess. A full backfill re-deriving the field from a still-available raw source is preferable to guessing when it's available.
- Establish ongoing ownership and process, since a schema registry alone doesn't prevent a NEW kind of divergence if there's no clear owner for the shared schema: designate who approves changes to the shared event schema, and require any change proposal to go through that owner rather than either team unilaterally deciding its version is correct.
Worked example. Suppose comparing the two teams' schemas shows both have a field called status, but one team's producer emits it as one of three string values (active, inactive, pending) while the other's emits it as a boolean (true/false), a genuine type-level divergence that likely happened when one team's field was originally boolean and the other team, building a similar-but-separate producer later, modeled the same concept differently without realizing a shared consumer expected consistency. Since the underlying business concept genuinely differs in expressiveness (three states versus two), simply mapping boolean-to-string automatically for the historical boolean data would lose information (true could map to active OR pending); the honest fix for historical data is flagging the boolean-sourced rows as only reliably distinguishing active-vs-not, without pretending to recover the active/pending distinction retroactively, while going forward, a schema-registry rule requiring both producers to emit the three-value string form closes the gap.
Trade-offs and pitfalls. It's tempting to solve type-level divergence with an automatic mapping to make the data LOOK consistent quickly, but as the boolean-versus-three-state example shows, an automatic mapping can silently manufacture false precision (pretending you know 'pending' when you only ever had 'true'); being honest about what can and can't be recovered is more valuable than a superficially clean-looking dataset that's actually wrong. A schema registry also only helps if BOTH teams' pipelines actually validate against it before publishing; adding the registry without also gating publishing on it leaves the same silent-drift risk in place.
Unlock Full Question Bank
Get access to all 10 Production Incident Diagnosis and Distributed Systems Troubleshooting interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.