AlgoViz

Debug a latency spike

easy 16 min

A p99 alert fires and users say checkout feels slow.

Video lesson · Chapter 1 of 8

The query that started too late

0:00 / 6:30

p99 alert to root cause in 90 seconds

1:30Reel coming soon

Debug a latency spike in one picture
Debug a latency spike in one picture

Theory

Read or listen first. About 1 min.

What it is

End-to-end latency includes queueing before work starts, service time, network transfer and scheduling. Parallel child spans can overlap, so adding every span duration can exceed request time. Follow the critical path and identify the longest avoidable interval before interpreting a slow request as a slow database.

Why it exists

At the same request rate, checkout p99 rises while query execution time barely changes. Trace the time before the query starts. Compare checked-out connections, pool wait and downstream limits by release. Increasing pool size may worsen database contention. Restoring a leaked lease or limiting fan-out can shorten the queue without increasing database concurrency.

If waits stay low but execution gets longer, examine plans and changed query mix at the same endpoint.

Fast queries behind a slow checkout

Checkout → Connection pool (wait for lease). Connection pool → Database (run query)
Checkout → Connection pool (wait for lease). Connection pool → Database (run query)

How it works

Step through the idea, or press Play.

Step 1 of 3

Alert and scope. Which endpoint, which percentile, since when, how many users

Understand it

Worked incident

Fast queries behind a slow checkout

ObservationPool wait p99 (ms)Interpretation
Baseline4A connection is available before the query starts.
Incident790A release retains leases and incoming requests wait almost a second.
After intervention7Restore lease cleanup and compare pool waits and end-to-end tails under matched traffic.
Illustrative measurements from the same workload at three checkpoints.

Choose the next investigation

If waits stay low but execution gets longer, examine plans and changed query mix at the same endpoint.
Whiteboard sketch: on the left, a chart where p50 stays flat while p99 jumps up at a dashed 'deploy' line. On the right, a trace waterfall: checkout, pricing, inventory, a long red 'pool wait' bar under a magnifying glass, and a tiny 'query' bar.
p99 jumps at the deploy while p50 stays flat. The trace shows the time going to waiting for a pool, not to the query.

Latency spikes are one of the most common production incidents, and one of the most common interview scenarios.

The investigation
  1. 1Read the alert
  2. 2What changed?
  3. 3RED + USE metrics
  4. 4Follow a trace
  5. 5Confirm in logs
  6. 6Mitigate
  7. 7Root cause

Step 1

Read the alert carefully

A good latency alert names a service, an endpoint or route, a percentile and a threshold, for example: checkout p99 above 1 second for 5 minutes. Before anything else, scope it:

  • One endpoint or all of them?
  • One region or every region?
  • All customers or one tenant?
  • Is the error rate rising too? Slow plus errors usually means timeouts.

Step 2

Ask what changed

Most incidents follow a change. Line up the start of the spike against:

  • Deploys and config or feature-flag changes, in this service and in the services it calls.
  • Traffic: total request rate, a single heavy customer, a bot, a marketing push, a batch job.
  • Dependencies: database, cache, queue, a third-party API, DNS or the network.
  • Infrastructure: node replacements, autoscaling events, noisy neighbours, a certificate or credential rotation.

Step 3

Use the right metrics

  1. 1

    RED, for each service

    Rate (requests per second), Errors (failed requests), Duration (latency distribution).

  2. 2

    USE, for each resource it uses

    For CPU, memory, disk, connection pools and thread pools: Utilization (how busy), Saturation (how much work is queued waiting), Errors.

Percentiles, not averages

An average mixes fast and slow requests into one number that describes almost nobody. If 98% of requests take 120 ms and 2% take 1.8 s, the average is about 154 ms, which looks fine, while one user in fifty waits almost two seconds. The p50 (median) tells you the typical request; p95 and p99 tell you the slow tail.

Python
import math# 100 requests: 98 fast, 2 very slow (milliseconds)latencies = [120] * 98 + [1800] * 2def percentile(values, p):    ordered = sorted(values)    rank = math.ceil(p * len(ordered) / 100)  # 1-based, nearest-rank    return ordered[max(rank, 1) - 1]print("average:", sum(latencies) / len(latencies), "ms")print("p50:    ", percentile(latencies, 50), "ms")print("p99:    ", percentile(latencies, 99), "ms")
The average looks healthy; p99 shows the slow tail. Nearest-rank percentiles, as in the Code tab.
Edit and run it in your browser

Step 4

Follow a trace

A distributed trace is a tree of spans, one per unit of work (an HTTP handler, a downstream call, a database query), each with a start time and duration. Pick a few slow traces from the spike window, not random ones, and look for the span that holds most of the time.

Step 5

Confirm with logs

Logs give detail that metrics leave out: the exact error, the request id, the tenant, the query text. Filter by the trace id or request id from the slow trace, or by the slow span's service and time window. You are looking for evidence that agrees with the trace, not a new theory.

Step 6

Mitigate before you fix

Other options:

  • Turn off the feature flag.
  • Add capacity if a resource is saturated.
  • Shed or rate-limit low-priority traffic.
  • Fail over to another region.
  • Serve a degraded response (skip recommendations, use cached prices).

Step 7

Root cause and follow-ups

After users are safe, explain the mechanism: what changed, why it made requests slow, and why the alerts, tests or canary did not catch it sooner. Turn that into follow-ups with owners:

  • A code fix.
  • A test or load test that would have caught it.
  • A dashboard or alert.
  • A safer rollout (canary or gradual rollout with automatic rollback).
  • A short blameless write-up.

Puzzle

Read the telemetry

Decide what is wrong before reading the answer. The checkout service was deployed at 14:00 with a new version of its inventory step.

Text
checkout (RED)       13:50          14:05  rate               410 req/s      405 req/s  errors             0.1%           0.6%  (all 504 timeouts)  average            128 ms         162 ms  p50                110 ms         112 ms  p99                240 ms         1,900 msinventory-db connection pool (USE)  in use             31 / 50        50 / 50  waiting callers    0              37slow trace 7f3a...  POST /api/checkout   total 1,870 ms  checkout.handler                        1,870 ms    pricing.get_quote                        38 ms    inventory.reserve                     1,790 ms      db.pool.acquire                     1,720 ms      db.query UPDATE stock                  18 ms14:05:12 WARN inventory waited 1712ms for db connection (pool=50 in_use=50) trace=7f3a...14:05:12 INFO inventory v2.14 reserve: opened transaction, calling pricing for promo check

What to do

  • Mitigate: roll back inventory v2.14.
  • Fix the root cause: do not hold a database transaction across a network call.
  • Follow up: alert on pool saturation, and add a load test for the promo path.

Traps in this data

  • Trusting the average: 128 → 162 ms looks harmless.
  • Blaming traffic: the request rate did not change.
  • Tuning the SQL: the query takes 18 ms; the time is spent waiting for a connection.

Summary

The whole topic in one minute.

The parent span can include acquiring a connection. An index changes query work after acquisition.

If waits stay low but execution gets longer, examine plans and changed query mix at the same endpoint.

  • Scope the alert first: which endpoint, percentile, region, tenant, and are errors rising too.
  • Most incidents follow a change: line the spike up against deploys, flags, traffic, dependencies and infrastructure.
  • RED for services, USE for resources; watch percentiles, never just the average.
  • Pick slow traces from the spike window and ask: is the slow span working or waiting?
  • Mitigate first (rollback is usually fastest), then find the mechanism and file follow-ups with owners.

Sources