Sub topic 16
Testing behavior beyond capacity
This chapter assumes you have read the earlier chapters on bounded queues, load shedding, and client signals. You should be able to read short Python asyncio examples and know what p99 latency means.
Most load tests answer the question "how much can we handle?" Overload tests answer a different one: "what happens at 2x that?" A service can pass the first test and still fail the second, because queues, retries, and shedding rules only show their behavior once demand exceeds capacity.
What an overload test must prove
An overload test checks that the controls from earlier chapters work together. Pass or fail should come from measurable properties, not from how the graphs look.
- Goodput stays near capacity. Goodput is the rate of requests that complete successfully and in time. It should plateau at capacity as offered load rises. It should not collapse.
- Latency of accepted requests stays bounded. Requests the service accepts should still finish in roughly the same time as at normal load.
- Excess load is rejected quickly and clearly. Rejections should be cheap, fast, and carry a 429 or 503 with Retry-After.
- Memory and queue depth stay flat. Neither should grow for the length of the test.
- The service recovers. When load drops back below capacity, latency and error rates return to baseline without a restart.
Open-loop versus closed-loop load
A closed-loop generator uses a fixed number of virtual users. Each user sends a request, waits for the response, then sends the next one. When the server slows down, the users slow down too, so offered load falls. The test ends up applying back pressure to itself and hides the overload you wanted to see.
An open-loop generator sends requests on a schedule, whatever the server does. Real traffic from many independent clients behaves this way. Use open-loop generators for overload tests.
A closed-loop generator also causes coordinated omission. While a user waits on one slow response, the requests it would have sent are never issued, and never measured. The slowest period of the test is under-represented in the percentiles. An open-loop generator avoids this because the schedule decides when each request starts. Measure latency from the scheduled start time, not from when the client got around to sending.
A runnable experiment
The script below simulates a server with 10 workers and a 50 ms service time, so capacity is about 200 requests per second. It compares an unbounded wait queue with a bounded one. The load generator is open-loop.
import asyncio
import time
SERVICE_TIME = 0.05
WORKERS = 10 # capacity is about WORKERS / SERVICE_TIME = 200 req/s
class Server:
def __init__(self, max_waiting=None):
self.slots = asyncio.Semaphore(WORKERS)
self.max_waiting = max_waiting
self.waiting = 0
async def handle(self) -> bool:
if (
self.max_waiting is not None
and self.slots.locked()
and self.waiting >= self.max_waiting
):
return False # shed immediately
self.waiting += 1
try:
await self.slots.acquire()
finally:
self.waiting -= 1
try:
await asyncio.sleep(SERVICE_TIME)
return True
finally:
self.slots.release()
async def one_request(server, scheduled, results):
ok = await server.handle()
results.append((ok, time.monotonic() - scheduled))
async def run(server, rate, seconds):
results = []
tasks = []
start = time.monotonic()
for i in range(int(rate * seconds)):
scheduled = start + i / rate
delay = scheduled - time.monotonic()
if delay > 0:
await asyncio.sleep(delay)
tasks.append(asyncio.create_task(one_request(server, scheduled, results)))
await asyncio.gather(*tasks)
return results
def p99(values):
values = sorted(values)
return values[int(len(values) * 0.99) - 1] if values else 0.0
async def main():
seconds = 4
for label, max_waiting in (("unbounded", None), ("bounded(20)", 20)):
for rate in (100, 200, 400):
results = await run(Server(max_waiting), rate, seconds)
ok_latencies = [lat for ok, lat in results if ok]
rejected = sum(1 for ok, _ in results if not ok)
print(
f"{label:12} offered={rate:3}/s "
f"goodput={len(ok_latencies) / seconds:6.1f}/s "
f"rejected={rejected:4} "
f"p99={p99(ok_latencies):.2f}s"
)
asyncio.run(main())Run it and compare the rows at 400 requests per second. Exact numbers vary by machine, but the shape should be stable.
- The unbounded server accepts everything. Its p99 grows to roughly the length of the test, because the backlog keeps growing while the test runs. Real clients would have timed out long before.
- The bounded server rejects about half of the requests. Its goodput stays near 200 per second. Its p99 stays near 0.15 s, which is the 20 queued requests plus one service time spread over 10 workers.
At 100 and 200 requests per second the two servers behave almost the same. Below capacity, the bound does nothing. That is why a test that never exceeds capacity cannot tell them apart.
Designing the test profile
A single flat run at high load is not enough. Use a profile with distinct phases and watch each one.
- Baseline. Record latency and error rate at about half of capacity. Every later phase is compared with this one.
- Ramp. Increase load steadily past capacity. Note the load at which rejections begin and whether goodput plateaus or drops.
- Hold. Stay at 1.5x to 3x capacity for long enough that a slow leak shows up. Memory growth and queue growth need minutes, not seconds.
- Drop and recover. Return to baseline load and measure how long latency takes to return to normal. A service that needs a restart to recover has failed the test.
Also test the cases that are less obvious.
- A spike. Jump from baseline to 5x with no ramp. This tests whether the bounds hold when the limiter has no time to adapt.
- A slow dependency. Add latency to a downstream call while keeping the request rate constant. Capacity drops without any change in traffic, and Little's law predicts in-flight work will rise.
- Misbehaving clients. Include clients that retry immediately and ignore Retry-After. Check that your retry budget and rate limits still protect the service.
- Mixed priorities. Send high and low priority traffic together and confirm that low priority is shed first.
What to measure
Collect these from both the generator and the server, and compare them.
| Signal | Source | What a healthy result looks like |
|---|---|---|
| Goodput | Generator | Plateaus near capacity, does not fall |
| p99 latency of accepted requests | Generator | Close to baseline, bounded by the queue limit |
| Rejection rate | Both | Rises with offered load, matches the excess |
| Time to reject | Generator | Much lower than normal request time |
| Queue depth and in-flight count | Server | Stays at or below the configured limit |
| Memory and open connections | Server | Flat during the hold phase |
| Recovery time | Generator | Short, and without manual action |
Compare client and server counts. If the generator sent 10,000 requests and the server logged 6,000, the missing requests were dropped somewhere you did not instrument, such as a connection backlog or load balancer.
Common mistakes
- Testing from one weak generator. If the load generator saturates its own CPU or network, it caps the offered load and you measure the generator. Watch the generator's own CPU and check that the achieved send rate matches the target.
- Averaging latency. Averages hide the tail. Report percentiles, and report accepted and rejected requests separately. Rejections are fast, so mixing them in makes latency look better than users experience.
- Testing only one instance. Per-instance limits behave differently behind a load balancer. Retries can land on another instance and shift the overload to it. Test the real topology at least once.
- Using unrealistic clients. Real clients retry. A generator that never retries cannot show retry amplification.
Turning the test into a regression check
Overload behavior drifts. A new dependency, a larger payload, or a changed timeout can quietly remove protection. Encode the pass criteria as assertions and run a shortened version of the test in CI or before each release.
def check_overload(goodput, capacity, p99_accepted, baseline_p99, max_queue, limit):
assert goodput >= 0.8 * capacity, "goodput collapsed under overload"
assert p99_accepted <= 3 * baseline_p99, "accepted requests became slow"
assert max_queue <= limit, "queue exceeded its bound"Choose thresholds from your own baseline and service level objectives. The values above are starting points, not standards.
Exercise
A team runs a load test with 200 virtual users. Each user sends a request, waits for the response, then sends the next. They double the number of users and see p99 latency rise only slightly and no rejections. They conclude the service handles 2x load. What is wrong with this test, and how would you fix it?
Show answer
The generator is closed-loop. When the service slows down, each user waits longer and sends fewer requests, so offered load falls and the test never drives the service past capacity. It also omits the requests that would have been sent during slow responses, which understates the tail latency. Fix it by using an open-loop generator that sends requests at a fixed rate on a schedule regardless of responses, measure latency from the scheduled send time, and ramp the rate to 2x or more of measured capacity.
Exercise
In the experiment above, the bounded server at 400 requests per second rejects about half of the requests, yet its goodput stays near 200 per second. Why is this a good result, and which two measurements would show that the unbounded server is doing worse?
Show answer
Goodput near capacity means the server spends its capacity on requests it can finish quickly, and the excess is turned away cheaply. The unbounded server accepts everything, so its queue and latency grow for as long as the overload lasts. Its p99 latency of accepted requests rises to about the test duration, and its queue depth (and memory) grows without a limit. Clients would time out before getting responses, so much of its work would be wasted.