Load checks the SLO at expected traffic, stress looks for the capacity limit, spike models a sudden jump, and soak looks for leaks. The result is read in percentiles p95 and p99, not the average, because response time has a long tail. Percentiles of different runs are computed from raw measurements rather than averaged, and k6 thresholds give CI an automatic verdict.
API · Load
The average response time is 300 ms, yet users complain about freezes. What is wrong with that number?
The dashboard shows an average of 314 ms and green ticks. Meanwhile support writes that a page sometimes takes four seconds to load. Both observations are true: the average simply erases the slow minority. This lesson answers two questions: which kind of load test fits which problem, and why the result is read in percentiles.
How it works
Load tests differ by the shape of the load curve over time, not by the tool. Each shape answers its own question:
Four load shapes
Figure 1. The curve decides the question: do we hold the SLO, where is the limit, do we recover from a burst, does anything leak over a long time.
Load checks that the SLO holds at the expected traffic. Stress raises the load above normal until something breaks: that finds the capacity limit and shows how the system degrades (slows down gradually or falls in a cascade). Spike models a sudden jump, such as a newsletter or a sale: it matters not only to survive but to recover afterwards. Soak holds a moderate load for hours so that memory leaks, an exhausted connection pool, growing logs or queues show up.
Why percentiles and not the average. Response time has a long tail: most requests are fast and a minority is very slow. The average mixes both groups into one number that describes neither:
1000 requests: 950 take 120 ms, 50 take 4000 ms
average = (950 * 120 + 50 * 4000) / 1000 = 314 ms looks fine
p95 = 120 ms (the 950th request is still fast)
p99 = 4000 ms (the slow tail)
p95 means 95% of requests are faster than this value, p99 the same for 99%. The tail matters more than it seems: a page is built from about ten API requests, and the chance that at least one lands in the slow 1% is already around 10%. That is why an SLO is written in percentiles: "p95 < 500 ms and p99 < 1200 ms at 200 requests per second, errors under 0.1%".
Example: a k6 scenario with thresholds
The test describes not "a number of users" but the arrival rate of requests (an open model), so a slow response does not reduce the load. Thresholds turn the SLO into an automatic verdict: if a threshold is breached, k6 exits with a non-zero code and CI goes red.
A closed scenario of "50 virtual users, each waiting for a response" behaves differently: when the server slows down, users send fewer requests and the system looks better than it is. This effect is called coordinated omission, and an arrival rate removes it.
Limits and alternatives
Percentiles of different runs or instances are not averaged: a mean of p95 values means nothing. Collect raw measurements or histograms and compute the percentile from them.
Few requests give an unstable p99: with 100 requests, p99 is decided by a single request. The tail needs hundreds or thousands of measurements.
The tool is chosen for the team: k6 (JavaScript scripts), Gatling (Java, Kotlin, Scala, and also JavaScript and TypeScript), JMeter (GUI and XML plans), Locust (Python). The shape of the scenario matters more than the brand.
A test on an empty database or a weaker environment measures the wrong thing. Data and configuration are brought close to production, and the threshold is compared with a baseline.
Common mistakes
Looking only at the average. The tail that every hundredth user sees stays invisible.
One test type "for everything". Load will not find a memory leak, and soak will not show behaviour during a spike.
Generating load from one weak laptop. The generator becomes the bottleneck instead of the service, so the numbers lie.
Running against production without agreement. A load test can take down shared services and trigger anti-fraud and rate limits.
Check yourself
After a release the average did not change, but p99 grew from 600 ms to 3 s. Is that a reason to worry and what can it mean?
Answer
Yes. The average still reflects the bulk of fast requests, while a slow minority could have become much slower: a new slow branch, a database lock, a cold cache or a rare query without an index. Next, look at which endpoints and parameters make up the tail.
For which test (load, stress, spike, soak) is a long history of memory metrics useful, and why?
Answer
For soak. A memory or connection leak shows as a slow linear growth that is invisible within the minutes of a load test. Soak holds a moderate load for hours, and the trend becomes obvious.
Related lessons: “Timeouts, retries and idempotency keys”, “A load test in practice: SLO, data, conclusions”, “Groups and a table of codes”.
In an interview.Junior: Load checks the expected load, stress looks for the limit, spike models a sharp burst, soak looks for leaks over a long time. I judge the result by p95 and p99, not by the average, because the average hides the slow tail. Middle/Senior: I write the SLO in percentiles and set them as k6 thresholds so CI gives the verdict itself. I pick an open model (arrival rate) to avoid coordinated omission, and I compute percentiles from raw measurements instead of averaging across instances.
Timeouts, retries and idempotency keys
A timeout bounds the wait, a retry repeats a call after a temporary failure, and an Idempotency-Key makes repeating a POST safe. A timeout does not report the outcome: the request may have run with only the response lost, so a retry without a key can double a payment. Only temporary failures are retried, with exponential backoff, jitter, the same key and a limit on attempts.
API · Resilience
A payment hangs on a timeout and the client repeats the request. How many times is the money charged?
A payment service answers in 30 seconds, the client waited 10 and repeated the request. The bank actually processed both. Now the customer has two charges for one purchase, and no "status 200" test saw it. This lesson is about three mechanisms that together make a call safe: a timeout, a retry and an idempotency key. Each one alone is dangerous.
How it works
The chain works like this. A timeout bounds the wait: without it a hung service holds the client's threads and connections, the request queue grows, and not just the dependency but the whole service goes down. A retry repeats the call after a temporary failure. An Idempotency-Key makes the repeat safe for methods that are not idempotent by themselves (POST).
The main danger is that a timeout does not report the outcome. The client knows only that no response arrived: the request may not have been accepted, it may have been executed, or only the response may have been lost. Without a key the client cannot tell these cases apart.
What the client knows after a timeout
Typical
A retry without a key
The server sees two independent POSTs and creates two transfers. The customer complains, and support hunts for the cause.
Better
A retry with one key
The server recognises the key, does not run the operation a second time and returns the stored response of the first attempt.
Figure 1. Retrying a non-idempotent POST is safe only together with a key that the client created once per operation.
What to retry. Temporary failures: a timeout, a dropped connection, 408, 429, 502, 503, 504. For 400, 401, 403, 404 or 422 a repeat changes nothing, because the problem is in the request itself. Per RFC 9110, GET, PUT and DELETE are idempotent and safe to repeat, while POST and PATCH need a key or another guard.
Backoff and jitter. Repeating at once means finishing off a service that is already choking. The delay grows exponentially (0.5 s, 1 s, 2 s, 4 s) and gets a random offset (jitter): without it thousands of clients that failed at the same moment retry at the same moment and create a new wave.
Example: a retry with backoff and a duplicate test
Here is a minimal wrapper. It repeats only temporary errors, respects Retry-After and otherwise waits a random time under an exponential cap:
const RETRYABLE = newSet([408, 429, 502, 503, 504]);
exportasyncfunctionwithRetry(call: () => Promise<Response>, max = 4) {
for (let attempt = 0; ; attempt++) {
let res: Response | undefined;
try {
res = awaitcall();
if (!RETRYABLE.has(res.status)) return res;
} catch {
// network error or timeout: treat as retryable
}
if (attempt >= max) thrownewError('gave up after ' + (attempt + 1) + ' attempts');
const retryAfter = Number(res?.headers.get('retry-after'));
const base = Math.min(8000, 500 * 2 ** attempt);
const delay = retryAfter > 0 ? retryAfter * 1000 : Math.random() * base; // full jitterawaitnewPromise((r) => setTimeout(r, delay));
}
}
Now a Playwright test. A stub of the payment provider (setStub is a hypothetical helper you write for your environment) answers in 5 seconds the first time. The client has a 2-second timeout, so the first attempt fails with an error and the retries go out with the same key until the server finishes the first attempt (while it runs, a correct server answers 409):
test('slow dependency: client times out, retries, one transfer', async ({ request }) => {
const key = crypto.randomUUID();
const send = () =>
request.post('/v1/transfers', {
headers: { 'Idempotency-Key': key }, // the same key on every attempt
data: { toAccount: 'UA21...', amount: 150, currency: 'UAH' },
timeout: 2000, // ms: fail fast instead of hanging
});
// the stub of the payment provider answers in 5 s the first timeawaitsetStub({ delayMs: 5000, times: 1 });
awaitsend().catch(() => undefined); // timeout: the client does not know the result// retry with the same key until the first attempt finishes (409 = still in progress)await expect
.poll(async () => (awaitsend()).status(), { timeout: 15_000 })
.toBeLessThan(300);
const list = await (await request.get('/v1/transfers?clientRef=' + key)).json();
expect(list.items).toHaveLength(1); // not two payments
});
The test checks not the status of the retry but the state of the system: the list has exactly one transfer. Without the key in the request this test goes red, which shows exactly why a retry is dangerous.
Limits and alternatives
The key must be stored on the server together with the response, not only in a cache that can be lost. The same key with a different request body should return an error (Stripe uses 400 or 409 depending on the case) instead of silently returning someone else's result.
A key lives for a limited time, usually a day. This is a contractual limit you learn from the documentation, and you test it.
Retries multiply load: if each of three service layers makes up to three attempts, one failure below becomes 27 requests. Retries are placed at one level and limited by a budget.
An IETF draft exists for the Idempotency-Key header, but it is not a final RFC yet: the behaviour of a given API is checked against its documentation.
An alternative to a key is natural idempotency, such as a PUT to a resource with a known id or a unique constraint in the database.
Common mistakes
Retrying any code. A repeat on 422 only loads the server and changes nothing.
Generating a new key for every attempt. Then the key protects nothing: the server sees different operations.
Retrying without a pause and without an attempt limit. That turns a dependency failure into a self-inflicted DoS attack.
One big timeout for everything. A total timeout of 60 s is above a user's patience. Better separate timeouts for connect and read plus an overall cap for the operation.
Check yourself
The client got a timeout on POST /transfers and does not know whether the transfer went through. What are the safe actions?
Answer
Repeat the request with the same Idempotency-Key, or re-read the state (GET the transfer by key or clientRef). You must not send a new request with a new key: if the first one went through, the transfer is duplicated.
Why is jitter needed if there is already an exponential delay?
Answer
The exponential spreads one client's repeats in time, but thousands of clients that failed at the same moment have identical delays and return in sync. A random offset scatters those repeats, so the server receives an even stream instead of waves.
Related lessons: “Kinds of load tests and percentiles”, “429, 503, Retry-After and the circuit breaker”, “PUT vs PATCH and Idempotency-Key in fintech”.
In an interview.Junior: Every call has a timeout, and only temporary errors may be retried, with a pause between attempts. For payments the repeat carries the same Idempotency-Key, and I check that the database holds one operation. Middle/Senior: A timeout does not report the outcome, so a retry without a key is dangerous. I check exponential backoff with jitter, respect for Retry-After, the attempt limit and that retries live at one level instead of multiplying across layers. Separately I test that the same key with a different body gives an error.
429, 503, Retry-After and the circuit breaker
429 means this client exceeded a limit, and 503 means the service temporarily cannot handle the request. Both may carry Retry-After with seconds or a date, and a client does not retry earlier and adds jitter. A circuit breaker opens after a threshold of failures and immediately returns an error or fallback, then closes again through trial requests; all three states are tested, including recovery.
API · Fault tolerance
A service returned 429 and the client retried at once. Why did it get worse?
A frontend shows search. The server returns 429 because the client exceeded a limit. The client repeats the request ten more times without pauses, the limit does not reset, and the user sees a spinner. Meanwhile the search dependency is down, and every request waits out its five-second timeout. This lesson is about how a server says "wait" (Retry-After), how a service protects itself from a chain failure (a circuit breaker) and what a tester checks.
How it works
429 Too Many Requests (RFC 6585) means this particular client exceeded a limit. 503 Service Unavailable (RFC 9110) means the service temporarily cannot handle the request: overload, a deploy, a dependency is down. The difference matters for diagnosis: 429 is fixed in the client, 503 points to the server's state. Both may carry a Retry-After header: either a number of seconds or an HTTP date.
HTTP/1.1 429 Too Many Requests
Retry-After: 30
Content-Type: application/problem+json
{ "type": "about:blank", "title": "Too Many Requests", "status": 429 }
HTTP/1.1 503 Service Unavailable
Retry-After: Wed, 11 Nov 2026 07:28:00 GMT
A correct client does not repeat earlier than told and still adds jitter, because many clients received the same time. Limits often have extra headers such as X-RateLimit-Remaining, but they are not finally standardised, so they are checked only against the documentation of a specific API.
A circuit breaker solves a different problem. When a dependency is unavailable, every call to it waits the full timeout, threads pile up, and little by little the service itself goes down. The breaker counts failures and after a threshold "opens": the next calls return an error or a fallback at once, without waiting. After a while it lets a few trial requests through and, if they succeed, closes again.
closed : calls go through, failures are counted
| failure rate above the threshold
open : calls fail at once (error or fallback), no waiting
| after the cool-down
half-open : a few trial calls
| success -> closed failure -> open
Without a breaker and with one
Typical
Without a breaker
Every request waits the dependency's 5 s timeout. Threads ran out, and the service is slow even for requests that do not need the dependency.
Better
With a breaker
After a series of failures, calls to the dependency instantly return an error or a fallback. The rest of the functionality works, and recovery is noticed without manual action.
Figure 1. A breaker does not heal the dependency. It stops its failure from taking other parts of the system down.
Example: what to check on a limit
The test reaches the documented limit, checks the header, waits and makes sure requests pass again:
test('limit: 429 carries a valid Retry-After and recovers', async ({ request }) => {
test.setTimeout(120_000); // Retry-After may be up to 60 slet res = await request.get('/v1/search?q=a');
for (let i = 0; i < 200 && res.status() !== 429; i++) {
res = await request.get('/v1/search?q=a'); // hit the documented limit
}
expect(res.status()).toBe(429);
const wait = Number(res.headers()['retry-after']);
expect(wait).toBeGreaterThan(0);
expect(wait).toBeLessThanOrEqual(60);
awaitnewPromise((r) => setTimeout(r, wait * 1000));
expect((await request.get('/v1/search?q=a')).status()).toBe(200);
});
A resilience scenario for the breaker is different: slow down or switch off the dependency (with a stub or a chaos tool) and check three things. The main service answers quickly with a controlled error or a fallback instead of hanging until the timeout. The metrics show the move to the open state. When the dependency returns, everything recovers without manual intervention.
Limits and alternatives
How a limit is counted depends on the algorithm (fixed window, sliding window, token bucket): at a window boundary a client may get twice the requests. That is the algorithm's behaviour, not necessarily a bug, and the documentation describes it.
A limit can apply per API key, user or IP. The test must use the same identifier and not mix counters.
A breaker with a fallback hides the failure from the user: that is useful, but you need metrics and an alert, otherwise nobody learns about the problem.
Next to it there are bulkheads (separate resource pools so one dependency does not exhaust all of them) and a client-side rate limiter. They complement the breaker rather than replace it.
Common mistakes
Ignoring Retry-After. The client retries earlier and stays in 429 longer.
Retrying 429 without an attempt limit. An endless loop never ends if the limit is permanent.
Mixing up 429 and 503. The first is about the client, the second about the service, and the reactions differ: slow down or wait for recovery.
Testing the breaker only when the dependency fails, not when it returns. Half of the defects are in recovery: the breaker never closes again.
Check yourself
The server returns 429 without Retry-After. What does the client do and what does the tester check?
Answer
The client falls back to its own backoff with jitter. The tester checks the documentation: if the header is promised, its absence is a defect. If not, they check that the client does not retry endlessly and shows a clear message.
The dependency recovered, but five minutes later the service still returns the fallback. What can be wrong with the breaker?
Answer
It does not move from open to half-open, or it does not close after successful trial requests. This is checked precisely on recovery: bring the dependency back, wait out the cool-down and require that responses become real again without a restart.
Related lessons: “Timeouts, retries and idempotency keys”, “Service headers: Retry-After, rate limits, Vary and security”, “Groups and a table of codes”.
In an interview.Junior: On 429 and 503 I check Retry-After and that the client does not retry earlier. A circuit breaker stops calling the dependency after a series of failures and quickly returns an error or a fallback. Middle/Senior: I test all three states: open after a series of failures, half-open after a pause and closing again after successful probes. Separately I check that the limit triggers at the right threshold, that the client adds jitter and that a breaker trip is visible in metrics and alerts.
A load test in practice: SLO, data, conclusions
A load test gives a decision-ready result only when the goal (SLI and SLO) and a baseline are set first. Then it needs a realistic scenario with varied data, warm-up with ramp-up, and analysis. Without an SLO a p95 figure means nothing, and one account and one endpoint leave the work to the cache. Percentiles, errors and server metrics reveal the bottleneck, and repeated runs show the spread.
API · Load
A test showed p95 = 400 ms. Is that good or bad, and can you trust it?
The test ran, k6 printed a nice table, and p95 is 400 ms. Without a criterion it is unclear whether that is a success. If every request in the test used one account, the data landed in the cache and the number means nothing at all. A load test without goals, a baseline and realistic data produces only pretty graphs. This lesson is about an order of work that makes the result fit for a decision.
How it works
The work goes in five steps, and each one guards against a particular false conclusion.
The order of a load test
Figure 1. Each step removes one false conclusion: no goal, nothing to compare with, unrealistic data, a cold start, the average instead of the tail.
1. Goals. An SLI (service level indicator) is a measurable metric, such as the share of successful responses or p99 latency. An SLO (objective) is the target for it: "p99 ≤ 800 ms and errors < 0.1% over a 15-minute plateau". Without an SLO, 400 ms is neither good nor bad.
2. Baseline. First measure one request and low concurrency on the same environment. Then the load grows, and changes are judged against the baseline, not against abstract "expectations".
3. A realistic scenario. A mix of requests as in production (say, 80% reads and 20% writes), not the single lightest endpoint. Different users and data: with one account everything lands in the cache and the result is optimistic. The data volume is close to production, because everything is fast on an empty database.
4. The run. Warm-up and a gradual ramp-up: cold caches, JIT and empty connection pools distort the first minutes. You measure the plateau and do not mix the first run into the results.
5. Analysis. Look at percentiles, the error rate (5xx, timeouts, 429), throughput and how latency grows with load: the point where the curve bends sharply upward is the capacity limit. Server resources (CPU, memory, the database connection pool, queues) show where the bottleneck is.
Example: a scenario with warm-up, a plateau and a threshold
The load stages describe the ramp-up, the plateau and the search for the limit. A threshold with abortOnFail stops the test if the system has already broken the SLO, so you do not burn time or take down a shared environment. Here the threshold covers the whole run, warm-up included; to judge the plateau alone, warm-up goes into a separate scenario and the threshold is set on http_req_duration{scenario:plateau}, while delayAbortEval keeps the first samples from aborting the test:
Data comes from a users file so every request goes from a different account. SharedArray keeps it in memory once for all virtual users:
import { SharedArray } from'k6/data';
import http from'k6/http';
const users = newSharedArray('users', () => JSON.parse(open('./users.json')));
exportdefaultfunction () {
const u = users[(__VU * 1000 + __ITER) % users.length]; // a different user each time
http.get(__ENV.BASE_URL + '/v1/accounts/' + u.accountId, {
headers: { Authorization: 'Bearer ' + u.token },
});
}
Now reading the result. Suppose at 100 requests per second p99 = 600 ms, and at 300 the latency jumped to 4 s and timeouts appeared. The limit lies between 100 and 300 requests per second. Server metrics showed the database connection pool at 100% while CPU stayed at 40%. The conclusion for the team: the bottleneck is the connection pool, not computation, so adding CPUs will not help.
Limits and alternatives
A test on a weaker environment proves nothing about production. The environment is described in the report: which instance, how many CPUs, what data volume.
A test against a service with mocked dependencies measures only the service itself. For the capacity of the whole path you need at least a surrogate of the real dependency with a realistic delay.
The load generator itself can become the bottleneck. Watch its CPU and network and, if needed, run a distributed test.
One run is not proof: estimate the spread between runs by repeating the test at least three times.
In production, monitoring and canary checks are preferred, and load tests stay on a test environment. A test on production needs agreement.
Common mistakes
One account and one endpoint. The cache answers instead of the system, and the numbers have no connection to real traffic.
Running without an SLO. There is nothing to judge the result by, and the discussion comes down to taste.
Measuring the cold first minutes. Warm-up is hidden or moved into a separate stage.
Concluding only the fact and not the cause. "Slow" without server metrics does not say what to fix.
Check yourself
A test with one test account showed p95 = 80 ms, while in production users complain about 900 ms. What is most likely wrong with the test?
Answer
All requests went to the same data, so the cache or hot database pages served them. You need different users and data with a volume close to production, and only then will p95 be comparable.
Why is warm-up not included in the measured part of the test?
Answer
Cold caches, empty connection pools and JIT warm-up make the first minutes slower than steady operation. If they are included in the measurement, p99 is inflated and does not reflect the plateau. Warm-up stays in the scenario but is excluded from the threshold.
Related lessons: “Kinds of load tests and percentiles”, “429, 503, Retry-After and the circuit breaker”, “Contract and performance: breaking change, 200 with an error, N+1”.
In an interview.Junior: First an SLO and a baseline, then a realistic scenario with different data and warm-up. I look at p95 and p99, the error rate and the point where latency grows sharply. Middle/Senior: I build the conclusion on server metrics: where the bottleneck is, the connection pool, the CPU or a dependency. I check that the generator did not become the limit, that the data and the environment configuration are comparable to production, and I repeat the run to estimate the spread. Thresholds in CI make the test a regression check instead of a one-off.