Chapter 08 / 10 · Foundations

Measuring before believing

p99 jumps from 4 ms to 900 ms after a release while the median stays put. Tracing it to a cause with percentiles, USE and the right profile.

This chapter lets you go from “it is slow” to a specific cause with evidence, without guessing. The previous chapter estimated; this one measures. The two go together. An estimate with no measurement hardens into folklore, and a measurement with no estimate has no way to notice that it is absurd.

The platform version of hitcount shipped a release on Tuesday. On Wednesday morning the dashboard showed the p99 latency of /hit at about 900 ms, up from 4 ms. The median had not moved from 3 ms. Readers did not notice, because hits are sent in the background. But the edge proxies in front of hitcount keep a limited pool of connections to it, and once a minute that pool filled and the proxies returned errors. Those hits were never counted.

Ask which latency got worse

A latency percentile is the value below which a given share of requests fall. The p50, or median, is the typical request. The p99 is the value only one request in a hundred exceeds. Different percentiles moving differently is the first piece of evidence, and averages hide it.

Here is Wednesday’s data, simplified. Over each minute, 97.5% of hits take about 3 ms. The other 2.5% are delayed by anything from 0 to 1.5 seconds, spread fairly evenly, averaging 750 ms. The mean is 0.975 × 3 ms + 0.025 × 750 ms ≈ 22 ms. On a dashboard showing only the mean, that reads as a mild regression from 3 ms. The median is still 3 ms. The p95 is still about 3 ms, because 95% of requests are unaffected. The p99 sits inside the delayed group: the slowest 1% of all requests is the slowest 40% of the delayed ones, so it lands around 0.6 × 1.5 s, about 900 ms.

Predict first

Before reading further, use the shape alone. The median and p95 are unchanged, about 2.5% of requests are delayed, and the worst delay is about 1.5 seconds. What kind of event produces that, and how often must it happen?

Show the worked answer

Something stops all requests at once, for about 1.5 seconds, regularly. If every request during a 1.5-second window is delayed, and 2.5% of requests are delayed, then the window covers 2.5% of the time: 1.5 s ÷ 0.025 = 60 seconds. So: something that blocks every hit for about a second and a half, once a minute.

A once-a-minute event in hitcount is easy to name: the snapshot, which the cost chapter moved to a one-minute interval. A slow dependency or a slow disk would produce a different shape, with delays spread across the minute rather than clustered.

Ask each resource three questions

Before opening the code, check the resources. Brendan Gregg’s USE method asks three questions of every resource the service uses. Utilisation: how much of the time is it busy? Saturation: how much work is queued waiting for it? Errors: is it reporting failures? Resources include the obvious hardware, CPU, memory, disk and network, and also software resources that requests queue for: locks, connection pools, thread pools. Saturation is the question people skip, and it is where latency hides, because a queue is time spent doing nothing.

ResourceUtilisationSaturationErrors
CPU~30%; one core pinned for ~1.5 s each minuterun queue shortnone
Memory1.2 of 2 GBno swapping, no reclaimno OOM kills
Diskidle, then a ~600 MB write each minutebrief queue during the writenone
Store mutexheld continuously for ~1.5 s each minute~1,500 goroutines waiting at the peaknone
Edge connection poola handful in use, of 1,000 allowedexhausted each minute503s returned to browsers

The table points straight at the mutex. Nothing is short of CPU or memory. Once a minute, one goroutine holds the store’s lock for a second and a half and every hit queues behind it; the queue holds connections open, and the edge pool runs out.

Why 1,500 goroutines, and how many hits were lost

The numbers in that table are not independent, and one small law connects them. Little’s law says that in any stable system, the average number of items inside it equals the rate at which they arrive times the average time each one spends inside: L = λ × W. It holds whatever the distribution of arrivals or service times, which makes it one of the most useful relations in capacity work.

On a normal minute, hits arrive at λ = 1,000 a second and each spends W = 3 ms in hitcount, so L = 1,000 × 0.003 = 3 hits in flight at any moment. That is why the edge proxies only ever had a handful of connections busy. During the stall, hits keep arriving at 1,000 a second and none leave. After 1.5 seconds, 1,500 are waiting, which is exactly the number of goroutines the dump found parked on the lock.

The same arithmetic prices the damage. Each waiting hit holds one of the edge pool’s 1,000 connections. The pool is full after one second of the stall, so for the remaining half second, about 500 hits are refused with a 503. Once a minute, out of 60,000 hits, that is about 0.8% of all hits never counted, concentrated on whichever pages happened to be read during the stall. A number like that turns “p99 is up” into a statement a product owner can weigh.

Little’s law also works in reverse, for sizing. If hitcount must handle 10,000 hits a second with each taking at most 50 ms, it must be able to hold 10,000 × 0.05 = 500 hits in flight. Pools, queues and connection limits smaller than that will reject work before the latency target is reached; much larger ones only let a stall build a bigger queue.

Read the profile that matches the problem

A CPU profiler interrupts the program many times a second and records the call stack each time. The aggregate shows where CPU time went. It is usually drawn as a flame graph: each stack is a column of boxes, callers below callees, and the width of a box is the share of samples in which that function was on the stack. Read widths, not heights. A tall, thin tower is a deep call chain that costs little; a wide, flat box is where the time is.

hitcount exposes Go’s profiler on an internal port, so a 30-second CPU profile is one command: go tool pprof http://hitcount:6060/debug/pprof/profile?seconds=30. The flame graph is dominated by encoding/json under (*store).snapshot. That is true and misleading. It tells us what the CPU does while the snapshot runs. It does not tell us why hits are slow, because a hit waiting for a lock uses no CPU at all and never appears in a CPU profile.

Waiting needs an off-CPU view. Go provides a mutex profile, which records where goroutines waited for locks and which code was holding them, and a block profile for other kinds of waiting. Enabled with runtime.SetMutexProfileFraction, the mutex profile shows nearly all lock waiting in (*store).hit, attributed to a holder in (*store).snapshot. A goroutine dump taken during the stall agrees: about 1,500 goroutines parked in sync.(*Mutex).Lock, called from hit. Now we open the code, and the release diff explains it:

// before: copy under the lock, encode and write after releasing it
s.mu.Lock()
rows := make([]row, 0, len(s.pages))
for _, p := range s.pages {
    rows = append(rows, row{p.Path, p.Views, p.ReadMs, p.Reads})
}
s.mu.Unlock()
return writeSnapshot(rows)

// after (Tuesday's release): stream straight from the map to save memory
s.mu.Lock()
defer s.mu.Unlock()
enc := json.NewEncoder(f)
for _, p := range s.pages {
    enc.Encode(p)
}

The change had a good reason. Copying 5 million rows of about 48 bytes allocated around 240 MB every minute, and on a busy day that copy pushed the container close to its memory limit. Streaming directly from the map removed the copy. It also moved the JSON encoding and the file writes inside the lock, and those take about a second and a half.

Reverting brings back the memory problem, so the fix has to address both. We split the store into 64 shards, each a map with its own mutex, choosing the shard by a hash of the path. The snapshot locks one shard, copies its roughly 78,000 pages (about 4 MB), unlocks it, writes them, and moves on to the next shard. A hit now waits at most for one shard’s copy, a few milliseconds, and the snapshot never holds more than 4 MB of copied rows at a time.

The cost: the snapshot is no longer a picture of a single instant. Shard 1 is copied a few seconds after shard 0, so the file mixes slightly different moments, and the saved total no longer equals the sum of the saved pages. We decided that was acceptable, because page counts are independent of each other, and we now recompute the total from the pages when loading rather than saving it. The other cost is code: /top now merges results from 64 shards. After the deploy, p99 returned to about 4 ms and the edge errors stopped. We kept the before and after graphs in the incident note, because they are the evidence that the fix fixed the thing.

With the stall gone, a CPU profile from an ordinary minute is worth reading for a different reason: it shows what hitcount spends its CPU on when nothing is wrong. The widest boxes are not ours. They are the kernel’s network code under the read and write system calls, and Go’s HTTP request parsing, with the runtime’s allocator and garbage collector a few percent each behind them. Our hit function, the code we wrote, is a sliver a few percent wide, and canonical, which decodes and normalises each path, is wider than hit itself.

That width puts a ceiling on any optimisation. If hit accounts for 3% of hitcount’s CPU, then making it infinitely fast saves 3%, and no more. This is Amdahl’s law applied to a profile: the speed-up from improving one part is limited by the share of the time that part takes. Before optimising a function, read its width, and work out the best possible result. For hitcount, the best available savings on an ordinary day are in fewer system calls per hit (batching hits at the edge) and fewer allocations per request, not in the handler.

Benchmarking without fooling yourself

Before a fix ships, we usually want a benchmark that shows it helps. Benchmarks are easy to get wrong in ways that produce confident, wrong numbers.

MistakeWhy the number is wrongWhat to do instead
One run, one numberrun-to-run noise is often larger than the changemany runs; compare distributions (Go’s benchstat does this)
Cold versus warmfirst runs measure caches filling and JITs compilingwarm up, then measure; state which you report
Reporting the meana few stalls vanish into a pleasant averagereport p50, p99 and the maximum
Toy data2,000 pages fit in cache; 5 million do notbenchmark at production size
Result never usedthe compiler removes work whose result is discardeduse the result, or Go’s b.Loop, which prevents this
Load generator waits for repliesit stops sending during a stall and records too few slow requestsgenerate load at a fixed arrival rate

The last row deserves a worked example, because it would have hidden Wednesday’s problem. Our first load test used 50 connections, each sending a request and waiting for the reply before sending the next. During a 1.5-second stall, each connection had one request waiting and sent nothing else, so the test recorded 50 slow requests. Real traffic does not wait: at 1,000 hits a second, about 1,500 hits arrive during the stall, and every one of them is slow. The test under-reported slow requests by a factor of thirty, and its p99 looked fine. This error is called coordinated omission. Tools that send requests at a fixed rate, regardless of replies, measure what users would actually experience.

One rule outranks all the others: change one thing at a time, keep the numbers, and write down the conditions, including data size, concurrency, and warm or cold. A performance claim without its conditions cannot be checked by anyone else, including you in a month.

Making the next regression visible sooner

Wednesday’s regression was found because someone looked at a p99 graph. It would have been found faster, and without luck, if the saturation signals from the USE table had been watched all along. After the incident we added three measurements to hitcount’s dashboard, each chosen because it would have moved before users were affected.

The first is the number of goroutines. By Little’s law it is the arrival rate times the time each request spends inside, so with a steady arrival rate it rises the moment requests start waiting, for any reason. On a normal minute it sits in the tens; a jump to the thousands is a stall, whatever caused it. The second is time spent waiting for the store’s locks, from the runtime’s mutex statistics, which separates “slow because busy” from “slow because queued”. The third is a latency histogram rather than a set of precomputed percentiles, so that any percentile over any window can be read later, including ones nobody thought to ask for in advance. The maths chapter explains why that last choice matters when several servers report.

We also run a continuous profiler that takes a short CPU and mutex profile from each instance every few minutes and keeps them for a month. Its overhead is small, around a percent, and it means the next investigation can compare “before the release” with “after the release” profiles directly, instead of reconstructing the past from graphs.

When to stop measuring

Measurement needs a target, or it never ends. hitcount’s is written down: p99 for /hit under 50 ms at the platform’s peak load, measured at the edge. While that holds, we do not profile for fun or shave microseconds off the handler, because no reader or blog owner would notice. Profiling effort goes where a target is missed or an estimate and a measurement disagree. When they disagree, one of them is teaching you something, and usually it is the estimate that needs correcting.

Two habits make the next investigation faster. Keep profiling endpoints enabled in production, on an internal port, because the problem you need to see is the one happening now. And keep a small set of benchmarks for the hottest paths in the repository, run on every change, with the noise caveats from the table in mind.

Wednesday’s CPU profile had one more detail we skipped: a few percent of samples in runtime.mallocgc and runtime.gcBgMarkWorker, and a memory graph with a sawtooth reaching 1.9 GB of a 2 GB limit. That is the Go runtime’s own work. The next chapter, Languages and runtimes, looks at what a runtime does on your behalf, what it charges, and when choosing a different language would change the answer.