Diagnosing a Latency Spike in a Distributed Ingestion Pipeline
System DesignModel answerLast updated
Walk through a systematic incident investigation: triage customer impact, correlate observability signals across service tiers, and separate root causes from cascading symptoms.
Scenario
You are the on-call engineer for a high-volume event ingestion platform. Connected edge devices stream sensor readings through a pipeline that includes an API gateway, a message broker, a pool of processing workers, a search cluster, and a relational metadata database.
At 14:15 UTC you receive a page. The gateway's p99 latency has jumped from ~40ms to over 6,000ms. Downstream consumers are seeing a flood of 504 Gateway Timeout errors. Simultaneously, alerts fire for elevated CPU across the worker pool and growing connection-pool backpressure.
Your Task
Describe how you would methodically investigate this incident, identify the true root cause, and distinguish it from the secondary failures it triggered.
Address each of the following in your answer:
-
First Response — Impact and Containment: Which signals do you look at in the first five minutes to understand customer impact? What actions can you take to reduce harm before you know the root cause?
-
Tracing the Bottleneck Through the Stack: How do you combine per-tier RED metrics (Rate, Errors, Duration), distributed trace spans, and structured logs to locate where in the call chain latency first diverged?
-
Proving Cause, Not Just Correlation: CPU saturation, thread-pool exhaustion, and connection timeouts are typically consequences, not causes. Walk through a concrete example of how you would confirm or rule out a database lock, a bad deployment, or a sudden traffic surge as the origin of this incident.
-
Closing the Incident and Preventing Recurrence: What measurable criteria tell you the system has fully recovered? What safeguards would you recommend to reduce the likelihood of a similar event?
Hints
Hint 1
Start by checking the change log against the incident timestamp before digging into metrics — most production outages are caused by something that changed recently, and this is the cheapest high-value check you can do.
Hint 2
To find which tier originated the problem, plot Duration for every hop on the same time axis. The tier whose latency rose first is the likely source; everything upstream is just waiting on it and will show the spike slightly later.
Hint 3
High CPU and pool exhaustion are saturation signals, not root causes. Ask: what are threads blocked waiting on? If DB query duration exploded while DB CPU is low, look for lock contention rather than compute pressure.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
What This Question Is Really Testing
The interviewer wants to see whether you debug from evidence or from instinct. Three habits separate strong candidates from weak ones: they contain customer impact before chasing root cause; they use timestamps and request rates to distinguish cause from effect; and they define "resolved" with numbers, not with "it seems fine now."
The trap in this scenario is that every alert is real, but most are downstream consequences of a single upstream event. Chasing CPU or pool exhaustion directly wastes time and can make things worse.
1. First Response — Impact and Containment
Assess scope in the first five minutes.
- Split gateway RED metrics by route, status code, region, and tenant. Is the entire platform affected, or one endpoint or customer segment?
- Check ingestion success rate and broker consumer lag. Telemetry pipelines can usually tolerate delay, but data loss is a different severity class.
- Look at the SLO error budget burn rate. A 14x burn rate means you need an incident commander, a comms owner, and a dedicated investigator — one person trying to do all three things simultaneously slows everything down.
Check the change log against 14:15 UTC before anything else. Deployments, feature flag flips, config pushes, schema migrations, autoscaling events, certificate rotations, and scheduled jobs (reindexing, backups) — all of them should be annotated on your dashboards. Most production incidents trace back to a change. This check takes 30 seconds and often gives you a candidate root cause immediately.
Safe mitigations you can apply before the full picture:
- Roll back any change that landed in the 30 minutes before onset. Rollback is reversible, so you don't need certainty first.
- Rate-limit noisy tenants at the gateway and return
429or503quickly rather than letting requests queue until they time out as504s. This frees connection slots for other traffic. - Shorten upstream timeouts so pools drain faster.
- Pause non-essential write paths: backfills, reindex jobs, bulk imports. These compete for the same database connections as the critical path.
- Avoid scaling the worker pool until you know the bottleneck. Adding workers against a locked database adds more contention, not more throughput.
2. Tracing the Bottleneck Through the Stack
Plot Duration per tier on a shared time axis. Lay out gateway, broker produce, workers, search cluster, and metadata DB side by side. The tier whose Duration diverges earliest is the originating layer. Every tier above it shows elevated latency slightly later because it is waiting on the tier below — that ordering is the signal.
Pull a representative slow trace. Take a trace ID from a request that took ~6,000ms and compare its span waterfall to a healthy trace from 14:00. The comparison usually makes the problem obvious:
| Span | Baseline | Incident |
|---|---|---|
| gateway handler | 40ms | 6,000ms |
| worker.enrich | 25ms | 5,950ms |
SELECT … FROM device_metadata | 3ms | 5,900ms |
When nearly all of the added latency sits in a single leaf span, that is the hop to investigate. Use trace exemplars — links embedded in metric histograms that point directly to a trace matching that data point — to jump from a latency dashboard to a slow trace without manual searching.
Pivot to structured logs. Filter by that trace ID, then broaden the query to the same service, error class, and time window. Group by error_type, host, and build_sha. Errors clustering on one build version or one host are strong discriminators that point toward a deployment issue rather than a load issue.
3. Proving Cause, Not Just Correlation
High CPU, pool exhaustion, and connection timeouts are saturation signals. Their mechanism: requests back up behind something slow, connection pools fill, retries amplify load, and CPU rises from retry storms and garbage collection. They tell you the system is under stress; they don't tell you why.
Test competing hypotheses with checks that can falsify them:
Traffic surge: If a surge is the cause, request rate rises before latency does, and throughput stays elevated or climbs. In this scenario, if gateway RPS was flat until 14:15 and then dropped as latency rose, a surge is ruled out — falling throughput under rising latency is the signature of saturation throttling a fixed arrival rate, not of more traffic arriving.
Faulty deployment: Onset aligns with a rollout window. Errors and high latency concentrate on the new build_sha or on canary hosts. Roll back one cohort and watch whether only that cohort recovers while others do not.
Database lock contention: DB span latency explodes while DB CPU may actually be low, because waiting threads are idle. Query pg_stat_activity and pg_locks (or SHOW ENGINE INNODB STATUS for MySQL) for blocked sessions and the blocking process ID.
Concrete example for the database-lock hypothesis:
Suppose a schema migration ran ALTER TABLE device_metadata ADD COLUMN … DEFAULT … at 14:12. This acquires an ACCESS EXCLUSIVE lock. Every worker query that touches that table queues behind it.
The evidence chain:
pg_locksshows ~400 sessions waiting on a single PID.- That PID is the migration process.
- The lock acquisition timestamp at 14:12 predates the gateway latency spike at 14:15 by about two minutes — consistent with pool backpressure building gradually.
- Terminating the blocking process with
pg_terminate_backendcauses DB span latency to fall from ~5,900ms back to ~3ms within seconds. Pool utilization drops next, then CPU, in that dependency order.
That dependency-ordered recovery is the causal test: the true root cause is the earliest anomaly whose removal causes every downstream symptom to resolve in the order you'd expect from the architecture.
4. Closing the Incident and Preventing Recurrence
Declare resolution only when all of the following hold and have been stable for a sustained window (30–60 minutes is a reasonable floor):
- Gateway p99 is back to the baseline range (~40–60ms).
- 5xx rate is below its pre-incident threshold (e.g., under 0.1%).
- Consumer lag is draining toward zero, and you have reconciled ingested event counts against device-side send counts to account for any data that was lost or needs replay from dead-letter queues.
- DB wait events, pool utilization, and worker CPU are all at baseline.
- SLO burn rate is back below 1x.
Post-mortem (blameless). Document a timestamped timeline, the full evidence chain above, contributing factors, and action items with named owners and deadlines. Common systemic fixes for this class of incident:
- Online migration tooling (
gh-ost,pg_repack) or enforcing alock_timeouton DDL to fail fast rather than block indefinitely. Require migration review before any DDL runs against production during peak hours. - Statement timeouts and bounded connection pools with explicit queue depth limits, so a slow dependency degrades gracefully rather than cascading.
- Circuit breakers per downstream dependency so a stuck database does not stall the entire worker pool.
- Retry budgets with jitter to prevent retry storms from amplifying saturation.
- An alert on DB lock-wait time or active waiting sessions — this would have paged on the cause at 14:12, three minutes before the gateway alert fired at 14:15.
- Change events annotated as vertical lines on every metrics dashboard so the correlation between a deploy and a spike is immediate.
Common Mistakes to Avoid
- Chasing the loudest alert. CPU and pool exhaustion alert first because they are direct symptoms. The root cause is usually quieter and earlier.
- Scaling up without diagnosing. Adding capacity against a database lock increases contention and can make recovery slower.
- Declaring resolution too early. Latency often dips as traffic naturally lulls, then spikes again. Require a sustained stable window, not a momentary drop.
- Skipping the change log. Engineers sometimes spend 45 minutes in traces before checking whether a migration ran three minutes before the alert. The change log takes 30 seconds.