Troubleshooting High Latency in a Production Microservice
System DesignModel answerLast updated
A guide on investigating and resolving a sudden 15x latency spike on a critical path service in a Kubernetes environment.
You are on call when an alert fires indicating that the 99th percentile (P99) latency for the Account-Profile-Service has jumped from 50 ms to 750 ms over a 10-minute window. This microservice is on the critical rendering path for the application's home feed.
Explain how you would systematically triage and remediate this incident:
- Scoping: What methods would you use to measure the blast radius and determine if the issue is global or isolated to specific cohorts (e.g., regions, versions, user segments)?
- Investigation: Which metrics, trace details, and logs would you inspect to differentiate between internal application bottlenecks (like thread starvation or garbage collection pauses) and external dependency issues (like database slowness or upstream API throttling)?
- Mitigation: How do you approach restoring service quickly while avoiding the destruction of key diagnostic data needed for later post-mortems?
- Resolution: What explicit signals and verification criteria must be met before officially concluding the incident?
Assume the system runs across multiple Kubernetes clusters using distributed tracing (e.g., OpenTelemetry/Jaeger), structured log collectors, and standard metric monitoring (e.g., Prometheus/Grafana).
Hints
Hint 1
Always start by checking for recent system modifications (deploys, configuration updates, or flag flips) and determining if the issue affects all endpoints or just a subset.
Hint 2
Use distributed tracing to isolate time spent inside the service versus time waiting on downstream calls or queueing.
Hint 3
Before taking destructive actions like restarting pods or rolling back code, isolate a single unhealthy instance to preserve memory dumps and traces.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
An effective candidate addresses production incidents with a methodical, calm, and structured approach. The primary objective during an active incident is to minimize customer impact as quickly as possible, followed by capturing enough state to diagnose the root cause accurately.
Step 0: Immediate Response & Coordination (First 2 Minutes)
- Acknowledge and Create Incident Space: Acknowledge the alert, open a dedicated incident bridge/slack channel, and take on (or assign) the role of Incident Commander (IC).
- Assess Home Feed Degradation: Verify whether the user experience is visibly degraded. Check if the home feed has a graceful degradation strategy (e.g., falling back to a cached profile or rendering without non-essential metadata).
- Check Recent Changes First: Over 80% of production outages stem from recent human-initiated changes. Immediately check:
- Recent deployments or rollback candidates within the last 30 minutes.
- Dynamic feature flag toggles or configuration changes.
- Infrastructure changes (e.g., Kubernetes node group resizing, database failovers, cloud provider incidents).
Step 1: Scoping the Blast Radius
Break down the metric breakdown across multiple metadata dimensions in Grafana/Prometheus:
- Deployment Version / Image Tag: Filter latency by
container_imageorapp_version. If latency is localized only to pods on versionv2.4.1whilev2.4.0remains at 50 ms, the issue is directly tied to the new build. - Geographic Region / Cluster: Group metrics by
clusterorregion. If onlyus-east-1is elevated, the issue points to regional infrastructure, a local database replica, or networking issues. - Pod-Level Distribution: Determine whether every pod is uniformly slow or if a small subset of "hot" pods is skewing the aggregate.
- All pods affected: Global resource contention, shared database issue, or global traffic surge.
- A few pods affected: Node-level noisy neighbors, uneven load balancing, or a sticky connection issue.
- Route / Endpoint: Compare latency across specific API endpoints (e.g.,
GET /user/avatarvsPOST /user/update).
# Example Prometheus query to identify latency by cluster and app version
histogram_quantile(0.99, sum(rate(http_request_duration_seconds_bucket{service="account-profile"}[5m])) by (le, cluster, version))
Step 2: Differentiating Internal Bottlenecks vs External Dependencies
Use distributed traces (Jaeger/Zipkin) as the first diagnostic step. Select multiple slow trace samples (>700 ms duration) and analyze the span hierarchy:
| Observation in Distributed Trace | Probable Cause |
|---|---|
| Large gap inside the parent span (child spans total 30 ms, but parent takes 750 ms) | Internal service bottleneck: thread contention, CPU throttling, high GC pause times, or synchronous lock acquisition. |
Long child span (e.g., postgres.query or redis.get span takes 700 ms) | External dependency slowness or network latency to that backend. |
| Time delay before the first span begins | Request queueing at the ingress layer or HTTP worker pool exhaustion. |
Diagnosing Internal Bottlenecks (USE Method)
- CPU Throttling: Query
container_cpu_cfs_throttled_periods_total. A pod may show low overall CPU usage (e.g., 40%), but if container limits are strict, thread execution can be choked by Linux CFS quota boundaries. - Garbage Collection / Memory: Review JVM/Go/Node runtime GC metrics. Long GC stop-the-world pauses will show up as periodic latency spikes matching the P99 graph.
- Pool Exhaustion: Check active/busy thread counts and HTTP/DB connection pool queue size. If connection pools are exhausted, requests spend hundreds of milliseconds merely waiting for a connection object.
Diagnosing External Dependencies
- Database Metrics: Check slow query logs, lock contention, active connection saturation, and replication lag on database replicas.
- Upstream APIs & Caches: Check cache hit ratios (e.g., a sudden Redis eviction storm) or circuit breaker status for downstream microservices.
Step 3: Fast Mitigation While Preserving Forensic Evidence
Evidence Preservation (1–2 minutes max)
Before applying destructive remediations (restarting, scaling down, or rolling back), take a brief snapshot to ensure a root-cause investigation is possible later:
- Quarantine One Pod: Cordon and remove one slow pod from the active Kubernetes Service endpoints (
kubectl label pod <pod-name> status=quarantined --overwrite). This stops incoming production traffic to it while keeping the process running. - Collect Runtime Diagnostics: Run a profiler, collect a thread dump (
jstack/ Go pprof), or grab a heap dump from the quarantined instance. - Log Snapshot: Save exemplar trace IDs and query logs from the affected time period.
# Quarantee a pod by updating its labels so the Service selector ignores it
kubectl label pod account-profile-7d94b-xyz production-traffic=false
Order of Operations for Mitigation
Apply mitigations one at a time and announce actions in the incident channel:
- Rollback: If a recent release or config change correlates with the spike, initiate an immediate rollback.
- Traffic Redirection / Region Drain: If the issue is isolated to a single Kubernetes cluster or availability zone, shift traffic at the global load balancer or DNS level away from the unhealthy cluster.
- Scale Out: If CPU saturation or request queueing is due to genuine traffic volume, scale out the deployment (
kubectl scale deployment account-profile --replicas=...). Note: Do not scale out if the bottleneck is a shared database, as adding app pods will worsen connection pool saturation on the database. - Load Shedding / Feature Toggles: Turn off non-essential downstream calls (e.g., recommendation badges) via feature flags, or apply rate limiting to aggressive callers.
Step 4: Verification and Incident Resolution
Do not mark an incident resolved immediately when the graph starts trending down. Validate recovery across all criteria:
- Golden Signals Returned to Baseline:
- P99 latency returns to target (< 50 ms) for at least 15 continuous minutes.
- Error rates drop back to nominal baseline levels (< 0.01%).
- Traffic throughput (RPS) matches expected volume patterns.
- Downstream & Infrastructure Health:
- Queue depths, CPU throttling rates, and connection pool queues have returned to zero/baseline.
- Database CPU and lock wait times are stable.
- Post-Mitigation Verification: Ensure that quarantined instances have been safely terminated and that temporary mitigations (like disabled feature flags) are tracked in follow-up tickets.
- Commence Post-Mortem Phase: Schedule a Blameless Post-Mortem to document timelines, root causes, systemic improvements, and action items.