Sub topic 12
Validating with Measurement and Load Tests, Then Revising Targets
A latency or throughput target is a hypothesis about how the system should behave. This chapter covers how to test that hypothesis and what to do when the result disagrees with it.
It assumes you have read the earlier chapters on percentiles, Little's law, latency budgets, SLIs and SLOs, error budgets, fan-out, and utilization. You should be comfortable reading short Python programs.
Why targets need validation
Every target so far rested on estimates: expected users, a peak factor, an average service time, a share of the latency budget. Estimates are usually wrong in at least one place. Validation finds out where, before users do.
Validation has two parts that answer different questions:
- Measurement of production traffic answers "what do real users experience today?"
- Load testing answers "what would happen at a load we have not seen yet?"
Neither replaces the other. Production data is realistic but covers only the load that has occurred. A load test can push past that load but only approximates real traffic.
Measuring production correctly
Measure the SLI you defined
Your SLI is a specific measurement, for example "the share of GET /search requests that complete in under 300 ms, measured at the load balancer". Validate that exact quantity. A server-side timer inside the application will miss time spent in queues, TLS handshakes, and the load balancer, so it reads lower than what the SLI promises.
Record latency at the point named in the SLI. If you also record at other points, such as the client, the gateway, and the database, you can see where the budget is being spent.
Aggregate percentiles correctly
You cannot average percentiles. Suppose instance A serves 9,000 requests with a p99 of 40 ms, and instance B serves 1,000 requests with a p99 of 900 ms. The average of the two p99 values is 470 ms, which is not the fleet p99. Use one of these instead:
- Ship raw samples and compute the percentile over the merged set.
- Use histograms with identical bucket boundaries, add the bucket counts together, and then read the percentile from the merged histogram.
Histograms are the usual choice because raw samples are expensive at scale. The cost is precision: a percentile read from a histogram is only as accurate as the bucket width around it. Put bucket boundaries close to your SLO threshold, so that 300 ms is a bucket edge rather than somewhere inside a wide bucket.
Check the sample size
A p99 needs enough samples to be meaningful. With 100 samples, the p99 is the single slowest request. With 1,000 samples, it is the 10th slowest. For p99.9, you want at least several thousand samples per measurement window. When traffic is low, use longer windows or merge windows rather than reading a percentile from a handful of requests.
Look at the distribution, not only the target percentile
Plot the latency distribution as a histogram or a percentile curve for p50, p90, p99 and p99.9. Look for these patterns:
- A second hump far from the main one often means a cache miss path, a retry, or a timeout.
- A p99 that sits exactly at a round number such as 1000 ms or 3000 ms usually means a timeout setting is shaping the tail.
- A p50 that is fine while p99.9 is huge points to rare events such as garbage collection pauses, lock contention, or a noisy neighbor.
Designing a load test
A load test sends synthetic traffic to a system and records the result. A useful one states its question before it starts: "Can the checkout service hold p99 under 300 ms at 1,200 requests per second for 30 minutes?"
Common test types
| Test type | Load shape | Question it answers |
|---|---|---|
| Baseline | Low, steady load | What is latency with no contention? |
| Step or ramp | Load increases in stages | Where does latency bend upward, and where does the system saturate? |
| Soak | Target load for hours | Do memory leaks, connection exhaustion, or slow compaction appear over time? |
| Spike | Sudden jump, then drop | How does the system react to a burst, and does it recover? |
| Failure injection | Target load plus a failed component | Does the SLO hold when an instance or dependency is lost? |
Match the test to the target
Use the numbers from earlier chapters to choose the load. If your estimate says peak is 800 requests per second and you want 50% headroom, test at 1,200. Also test beyond that to find the actual limit. Knowing the limit tells you how much real headroom you have.
Use Little's law to sanity-check the test itself. If the target is 1,200 requests per second at 50 ms average latency, about 60 requests are in flight on average. If your load tool is configured for 20 concurrent connections, it cannot produce that load without raising latency. The tool becomes the bottleneck.
Make the test realistic
- Use a request mix that matches production. A test that only sends cache hits will pass easily.
- Use realistic data sizes and key distributions. If production traffic concentrates on a few hot keys, uniform random keys will understate contention.
- Warm caches and connection pools first, then discard the warm-up period from the results. Test cold starts separately if they matter.
- Run the test against an environment sized like production. A test on a single small database says little about a sharded one.
- Keep the load generator off the machines under test, and watch its own CPU. A saturated load generator reports false latency.
Open-loop versus closed-loop load
This is the most common error in home-made load tests.
A closed-loop generator has a fixed number of workers. Each sends a request, waits for the response, then sends the next. When the system slows down, the workers send fewer requests, so the generator quietly reduces the load exactly when the system struggles. It also records only the requests it actually sent. This is called coordinated omission, and it makes tail latency look much better than it is.
An open-loop generator sends requests on a schedule, such as 500 per second, whatever the system is doing. Real users do not wait politely for a slow system to catch up, so this is much closer to real traffic. Measure each latency from the time the request was meant to be sent, not from the time the generator got around to sending it.
The following program is a small open-loop step test against a simulated service. The service has 10 slots and a mean service time of 20 ms, so its capacity is about 10 / 0.020 = 500 requests per second.
import asyncio
import math
import random
import time
def percentile(samples, p):
ordered = sorted(samples)
rank = math.ceil(p / 100 * len(ordered))
return ordered[rank - 1]
async def fake_service(slots):
# Waiting for a slot is queueing time, which a real service also has.
async with slots:
await asyncio.sleep(random.expovariate(1 / 0.020)) # mean 20 ms
async def run_step(rate, duration_s, slots):
latencies_ms = []
async def one_request(intended_start):
await fake_service(slots)
# Measured from the intended start, so queueing delay is not hidden.
latencies_ms.append((time.perf_counter() - intended_start) * 1000)
start = time.perf_counter()
tasks = []
for i in range(int(rate * duration_s)):
intended_start = start + i / rate
delay = intended_start - time.perf_counter()
if delay > 0:
await asyncio.sleep(delay)
tasks.append(asyncio.create_task(one_request(intended_start)))
await asyncio.gather(*tasks)
return latencies_ms
async def main():
slots = asyncio.Semaphore(10)
for rate in (100, 300, 450, 550):
lat = await run_step(rate, 3, slots)
print(
f"{rate:>4} req/s "
f"p50={percentile(lat, 50):7.1f} ms "
f"p99={percentile(lat, 99):7.1f} ms"
)
asyncio.run(main())The exact numbers differ from run to run. The pattern is stable: at 100 req/s the p99 stays close to a few service times. Near 450 req/s it rises noticeably, even though the average load is still below capacity. At 550 req/s, above capacity, the queue grows for the whole step and both p50 and p99 climb sharply. This is the queueing behavior from the utilization chapter, observed directly.
Comparing results with the SLO
Turn the raw results into a pass or fail decision with an explicit rule. The function below checks both a latency SLI and an availability SLI.
import math
def percentile(samples, p):
ordered = sorted(samples)
rank = math.ceil(p / 100 * len(ordered))
return ordered[rank - 1]
def check_slo(latencies_ms, failed, total, p99_target_ms, success_target):
p99 = percentile(latencies_ms, 99)
success_rate = (total - failed) / total
return {
"p99_ms": p99,
"p99_ok": p99 <= p99_target_ms,
"success_rate": round(success_rate, 4),
"success_ok": success_rate >= success_target,
}
samples = [40] * 985 + [250] * 10 + [800] * 5
print(check_slo(samples, failed=3, total=1000,
p99_target_ms=300, success_target=0.999))
# {'p99_ms': 250, 'p99_ok': True, 'success_rate': 0.997, 'success_ok': False}The latency target passes while the availability target fails. Report each SLI separately, because a single "pass" hides which one needs work.
Also count slow requests as part of the error picture when your SLO is a threshold such as "99% of requests under 300 ms". A request that returns in 5 seconds counts against the objective exactly as a failed request does.
Using error budgets and burn rate to decide
The error budget turns validation into a decision. Burn rate is the observed error rate divided by the error rate the SLO allows:
slo = 0.999
allowed_error_rate = 1 - slo # 0.001
observed_error_rate = 0.005 # 0.5% of requests failing or too slow
burn_rate = observed_error_rate / allowed_error_rate
window_days = 30
print(round(burn_rate, 1)) # 5.0
print(round(window_days / burn_rate, 1)) # 6.0 days until the budget is goneA burn rate of 1 uses the budget exactly over the window. A burn rate of 5 uses it up in one fifth of the window. Teams commonly alert on a high burn rate over a short window, which catches fast incidents, and on a lower burn rate over a long window, which catches slow leaks. The thresholds are a team decision, not a standard.
Interpreting a miss
When results fall short, find out which of three situations you are in before changing anything:
- The system is slower than the design assumed. A component takes more of the budget than allocated. Profile it, fix it, or rebalance the budget.
- The load is different from the estimate. Peak factor, request mix, or growth was wrong. Update the load estimate and redo the capacity arithmetic.
- The target is unrealistic. The target asks for more than the cost, the architecture, or the dependencies can deliver.
Fan-out deserves a specific check. If a request waits on 10 independent calls and each meets its own p99, about 9.6% of end-to-end requests still hit at least one slow call. When the end-to-end tail is worse than the per-component numbers suggest, compare the two before blaming a single component.
Revising targets
Targets should change when evidence says they should. Revise them on purpose, with a record of why, rather than editing numbers until the dashboard turns green.
Reasons to tighten a target:
- The system meets the SLO with a very wide margin for months, and user research or product needs would benefit from better latency.
- A competitor or a new feature raises user expectations.
Reasons to loosen a target:
- Meeting it needs spending that the product value does not justify.
- Users show no change in behavior between, say, 300 ms and 500 ms at p99.
Reasons to change the design instead:
- The target is justified by the product, and the miss comes from queueing at high utilization, a slow dependency, or fan-out. Options include adding capacity, caching, hedged requests, tighter timeouts, or concurrency limits.
Rerun the load test after every significant change to the system or the target. Re-validate also after traffic grows by a large factor, after a major dependency change, and on a regular schedule. A target that was valid a year ago may not hold against today's traffic.
Common mistakes
- Reporting the mean latency from a test and calling it validation.
- Averaging per-instance percentiles to get a fleet percentile.
- Using a closed-loop generator and missing the queueing delay.
- Testing only at the expected peak, so the limit and the real headroom stay unknown.
- Forgetting the warm-up period, which skews early samples.
- Running the test once and treating a single result as the truth. Repeat it, and compare the spread between runs.
- Lowering the target to match the measured result without asking whether users are affected.
Exercise
A team runs a load test with 50 worker threads. Each worker sends a request, waits for the response, and sends the next one. The service slows down halfway through and the report shows a p99 of 180 ms against a target of 250 ms. The service's real production p99 during the same slowdown was 2 seconds. Name the testing flaw, explain why it produced the low number, and describe a fix.
Show answer
The flaw is coordinated omission from a closed-loop generator. When the service slowed, each worker spent longer waiting, so the generator sent fewer requests during the slow period and recorded far fewer slow samples. Requests that real users would have sent during the slowdown were never sent, so their waiting time never entered the results. The fix is to use an open-loop generator that sends requests at a fixed rate on a schedule and measures each latency from the intended send time. Also check that the load generator achieves its requested rate.
Exercise
A service has a 99.9% success SLO over 30 days. During a load test, 0.4% of requests fail at the target load. What is the burn rate, and how many days would the error budget last if production behaved the same way?
Show answer
The allowed error rate is 1 - 0.999 = 0.001. The observed rate is 0.004, so the burn rate is 0.004 / 0.001 = 4. The 30-day budget would last 30 / 4 = 7.5 days. The test result means the system should not go to production at that load without a fix or a lower load limit.