Part 01 · Measuring Performance

Latency and Throughput in Production

LatencyThroughputSaturation

The Eid sale is next week. The two numbers that tell you if checkout will hold, and how they move together under load.

⏱ 9 min · Station 2 of 95

The problem

The Eid sale is next week, and leadership asks one question: "will checkout hold?" The on-call dashboard shows traffic (steady) and errors (zero), and the honest answer from those two graphs is "it looks fine". Then, during a routine afternoon, the database gets a few milliseconds slower (a noisy neighbour, a backup, a bigger table). Traffic stays the same. Errors stay at zero. Customers are waiting six times longer for every product page, and nothing on that dashboard moves.

In production you don't run load tests to find out how the system behaves. You read the numbers it reports about itself, continuously. Which numbers, and how they move together, decides whether you see trouble coming.

The idea

Three numbers describe a running service, and they're tied together:

  • Throughput (rate): requests completed per second. In production this is mostly set by demand: how many users arrive. As long as the service keeps up, throughput equals arrivals, whatever happens to latency.
  • Latency: how long each request takes, as percentiles (p50, p95, p99). This is what users feel and what changes first when something gets slower.
  • Saturation: how much work is waiting or in progress, here http_requests_in_flight. It connects the other two: on average, requests in flight = throughput × latency.

So when a dependency slows down:

  • Below capacity, throughput stays flat (users still arrive at the same rate), latency rises, and in-flight rises with it. No errors yet.
  • Past capacity, the service can't keep up: throughput drops below arrivals, in-flight shoots up to whatever limit exists (threads, connections, client patience), and latency runs to timeouts. Errors come last.

A dashboard of rate and errors only sees the second case, and late.

How it works

The shop records every request in a histogram and a counter; Prometheus scrapes them every 5 seconds. From those:

rate/s     = sum(rate(http_requests_total{route="GET /products/{id}"}[10s]))
p95        = histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket{...}[10s])))
in flight  = max_over_time(http_requests_in_flight[10s])

rate(...[10s]) turns an always-growing counter into "per second over the last 10 seconds". histogram_quantile estimates the 95th percentile from the histogram's bucket counts. A 10-second window reacts fast; real dashboards often use 1 to 5 minutes to smooth noise.

During the incident below, each product page runs three queries, each now 5 ms slower: about 15 ms more per page. With 300 requests per second arriving, Little's Law says in-flight should rise by about 300 × 0.015 ≈ 4.5. The shop still has spare capacity, so throughput doesn't change at all.

Predict first

300 requests/s arrive steadily. The database gets 5 ms slower per round trip (a product page makes 3 round trips). What do the shop's metrics show?

Visual

database +5 msrate/s301/sp9542 msin flight110 s50 s100 s140 stimethroughput doesn't move: users keep arriving at 300/sp95 goes from 4.8 to ~35 ms, requests in flight from 2 to ~8a dashboard that only shows traffic and errors would look fine
The shop's own metrics during a slow-database incident (50 s to 100 s). Throughput doesn't move; p95 and requests in flight jump, then recover when the database does.

Common misconception

"If throughput and error rate look normal, the service is healthy." Throughput is set by your users, not your service, until the service falls over. Error rate rises only when requests fail outright. Everything between "fine" and "falling over" (the zone where users wait several times longer) shows up only in latency and saturation.

"Average latency is enough to watch." The average blends fast and slow requests and moves late. The next two lessons show why percentiles, and which ones, are the numbers to watch.

Break it, then fix it

Measured on the lab (Intel i3-10110U; the shop and PostgreSQL each on one CPU thread; Prometheus scraping every 5 s). incident.sh sends a steady 300 requests per second for 150 seconds. At 50 seconds it adds 5 ms to every packet PostgreSQL sends (netem.sh), at 100 seconds it removes it. Then it reads the shop's metrics from Prometheus as a table, one row per 10 seconds, using promrange.sh:

#!/bin/sh
# Print a small time table from Prometheus: one row per STEP seconds over the last SECONDS.
#   ./promrange.sh 120 10 'label=query' 'label=query' ...
secs=$1; step=$2; shift 2
python3 - "$secs" "$step" "$@" <<'PY'
import json, sys, time, urllib.parse, urllib.request
secs, step, pairs = int(sys.argv[1]), int(sys.argv[2]), sys.argv[3:]
end = time.time(); start = end - secs
cols, data = [], []
for p in pairs:
    label, q = p.split("=", 1)
    url = "http://localhost:59090/api/v1/query_range?" + urllib.parse.urlencode(
        {"query": q, "start": start, "end": end, "step": step})
    r = json.load(urllib.request.urlopen(url))
    series = r["data"]["result"]
    vals = {float(t): float(v) for t, v in series[0]["values"]} if series else {}
    cols.append(label); data.append(vals)
times = sorted(set().union(*[d.keys() for d in data]))
print("   t " + "".join(f"{c:>14}" for c in cols))
for t in times:
    row = []
    for d in data:
        v = d.get(t)
        row.append("-" if v is None else (f"{v:.0f}" if v >= 100 else f"{v:.3g}"))
    print(f"{int(t - times[0]):>4} " + "".join(f"{x:>14}" for x in row))
PY
cd ../../lab
CACHE=off docker compose up -d api >/dev/null 2>&1; sleep 3
./k6.sh product.js -e RATE=80 -e DURATION=15s >/dev/null 2>&1              # warm up
./k6.sh product.js -e RATE=300 -e DURATION=150s >/dev/null 2>&1 &            # steady traffic
sleep 50;  ./netem.sh db delay 5ms            # 50 s in: the database gets slower
sleep 50;  ./netem.sh db off                  # 100 s in: fixed
wait; sleep 6
P='GET /products/{id}'
./promrange.sh 150 10 \
  "rate/s=sum(rate(http_requests_total{route=\"$P\"}[10s]))" \
  "p95 ms=1000*histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket{route=\"$P\"}[10s])))" \
  "in flight=max_over_time(http_requests_in_flight[10s])"
   t         rate/s        p95 ms     in flight
   0            180          7.83             3
  10            300           4.8             2
  20            300          4.92             2
  30            300          4.84             2
  40            300          4.87             2
  50            299            24             8
  60            300          34.1             8
  70            299          30.1            11
  80            300          31.7             7
  90            300          35.5             7
 100            301          42.4             7
 110            300          4.77             2
 120            300          4.78             1
 130            300          4.93             2
 140            300          4.87             3
 150            143          4.76             2

Reading it:

  • 0 to 40 s: normal. 300 per second, p95 about 4.8 ms, 2 requests in flight. (The first row is the test ramping up.)
  • 50 to 100 s: the incident. Throughput: 299 to 301, unchanged. p95: 24 to 42 ms, five to nine times higher. In flight: 7 to 11 instead of 2. Zero errors.
  • 110 s on: fixed. p95 back to 4.8 ms within one 10-second window. (The last row is k6 finishing.)

Check it with Little's Law: in flight ≈ 300 × 0.025 s (roughly the average during the incident) ≈ 7.5. The measured 7 to 11 matches.

The fix here was removing the delay. In a real incident, the same three numbers tell you where to look: throughput flat + latency up = something got slower, not more traffic.

Engineering insight

  • Watch rate, latency percentiles and saturation together, per endpoint. That trio (plus errors) is the RED method you'll build in the observability part. Latency and saturation are your early warning; errors are the last signal.
  • Distinguish "more traffic" from "slower work". Rate up + latency up: load. Rate flat + latency up: a dependency or a change got slower. Rate down while arrivals didn't change (check the load balancer's count): you're past capacity and queueing.
  • Windows matter. A 10-second rate shows a spike as it happens and is noisy; a 5-minute rate is smooth and late. Alerting usually wants minutes; debugging wants seconds.
  • Big companies alert on latency SLOs, not on CPU. "p99 checkout latency over 300 ms for 5 minutes" catches this incident; "database CPU over 80%" wouldn't (the database was barely busier).

Key takeaway

In production, throughput follows demand until the service runs out of capacity, so it hides slowdowns. Latency percentiles and requests in flight move first: here a 5 ms database slowdown raised p95 six to nine times with throughput unchanged and zero errors. Watch all three together.

Practice

Objective: see the other regime: a slowdown that pushes the service past capacity.

Challenge: repeat the incident with ./netem.sh db delay 20ms (about 60 ms more per page). Before running, predict throughput, p95 and in-flight during the incident. Hint: the shop's database pool has 10 connections.

Expected result: a table where throughput itself drops, and an explanation of the number it drops to.

Hint 1

Each page holds a database connection for about 3 × 20 ms plus the work.

Hint 2

With 10 connections, at most 10 pages are being built at once. How many per second is that?

Hint 3

Little's Law in reverse: throughput ≤ connections / time per page.

Solution
   t         rate/s        p95 ms     in flight
   0            300          4.77             1
  10            300           4.8             2
  20            300          4.76             2
  30            126          3690           501
  40            149          4875           501
  50            150          4875           501
  60            153          4875           500
  70            342           597           210
  80            300          4.79             2
  90            300          5.63             2
 100              0           nan             1

Throughput fell from 300 to about 150 per second: 10 connections / ~65 ms per page ≈ 154. In flight jumped to 500 (k6's limit on virtual users; real users would keep piling up), and p95 hit the histogram's top bucket (5 s), so Prometheus can only say "about 5 seconds or more". When the delay was removed, the backlog drained (342 per second for one window) and everything returned to normal. Same kind of incident, four times the delay, and the service went from "slower" to "can't keep up": that's the cliff from the capacity lessons, seen from inside.

Interview check

Q: Your API's request rate and error rate look normal, but customers complain the site is slow. What do you look at?

Model answer

Latency percentiles (p95/p99) per endpoint and saturation signals (requests in flight, queue lengths, connection pool usage). A dependency or a recent change may have made requests slower while the service still keeps up, so rate stays flat and nothing errors. Then I'd compare when latency rose with deploys and dependency metrics, and use traces to see which part of the request got slower.

Q: During an incident, your service's throughput dropped from 300 to 150 requests per second, but the load balancer still receives 300. What's happening?

Model answer

The service is past capacity: it completes only 150 per second, so the other 150 per second are queueing (in flight grows without bound) or timing out. Something limits concurrency (a pool, threads, a slow dependency): capacity = concurrency limit / time per request. Find what made requests slower or what limits concurrency, and shed or reject excess load so the requests that are served still succeed quickly.

Station stamp

Finish the chapter

Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.

Go Pro to earn XP →