読み物Testing · Quality Engineering

Level: Pro

Performance and Reliability Testing: Load, Stress, Soak Testing, and Benchmarks

Measure latency percentiles, throughput, and errors against goals; run load, stress, spike, and soak tests with k6; and benchmark code, with real results including a failed threshold.

Edeeson Opina9 min read

A Pro lesson card: lesson 11 of the Software Testing & Quality Engineering series, Performance and Reliability Testing: Load, Stress, Soak Testing, and Benchmarks, with the Miso fox holding a camera.

What you’ll learn

  • Measure latency percentiles, throughput, error rate, and saturation
  • Choose between smoke, load, stress, spike, soak, and breakpoint tests
  • Write k6 tests with thresholds as pass or fail goals
  • Benchmark code realistically and profile before optimizing
On this page
  1. Before you start
  2. The metrics that matter
  3. Kinds of performance tests
  4. Testing in a realistic environment
  5. A load test with k6
  6. A stress test: where it breaks
  7. Common bottlenecks
  8. Reliability: soak and failure testing
  9. Benchmarks: measuring code, not systems
  10. Performance budgets in CI
  11. Common mistakes and troubleshooting
  12. Practical exercise: find the breaking point
  13. Key takeaways
  14. References
  15. What's next

A feature that works for one user can fail for a thousand. Pages slow down, requests time out, memory creeps up until the server restarts, and none of it shows in a unit test. Performance and reliability testing answer different questions: how fast is it, how much can it handle, where does it break, and does it stay healthy over time? This lesson explains those questions and the metrics that answer them, independent of any tool, then demonstrates them with k6 load tests and code benchmarks, with real results, including a test that passes at normal load and fails its threshold under stress.

Before you start

You should be comfortable with automated testing and CI from the Intermediate level, especially Automated Testing in CI/CD: Coverage, Static Analysis, and Quality Gates. Run load tests only against systems you own or are explicitly authorized to test: a load test against someone else's server is indistinguishable from an attack.

The metrics that matter

  • Latency (response time): how long one request takes. Report percentiles, not just averages. The 95th percentile (p95) is the time 95% of requests beat; the slowest 5% are often what users remember. An average of 200 ms can hide that one request in twenty takes three seconds.
  • Throughput: how many requests or operations per second the system completes.
  • Error rate: the share of requests that fail or time out. A fast system that returns errors isn't fast.
  • Saturation and resources: CPU, memory, database connections, queue lengths. They show *why* latency rises.
  • Stability over time: memory that grows without bound, connections that leak, performance that degrades after hours.

Set goals before testing, ideally from real user needs: for example, "p95 below 300 ms for search, under 1% errors, at 200 concurrent users." Without a goal, a load test produces numbers but no decision.

Kinds of performance tests

Grafana's k6 documentation describes a common set of test types, distinguished by the load pattern:

  • Smoke test: minimal load, to check the script and system work at all.
  • Average-load test: typical production traffic, to confirm the system meets its goals under normal conditions.
  • Stress test: load above normal, to see how the system behaves when it's pushed.
  • Spike test: a sudden surge, like a sale starting or a link going viral.
  • Soak (endurance) test: normal load held for hours, to reveal leaks and slow degradation.
  • Breakpoint test: load that keeps increasing until something fails, to find capacity limits.

These are principles, not features of one tool. You could run each of them with k6, Gatling, Locust, JMeter, or a script of your own.

Testing in a realistic environment

Load test results are only as meaningful as the environment:

  • Test a production-like setup: same instance sizes, database size and indexes, caches, and network path. A laptop result says little about production.
  • Use realistic data volumes; a query that's fast on 100 rows can be slow on ten million.
  • Generate load from a separate machine, so the load generator doesn't compete for CPU with the system under test.
  • Mix realistic behavior: think times between actions, a mix of endpoints, cached and uncached requests.
  • Watch the server's own metrics (CPU, memory, database) during the test, not only the client's view.

A load test with k6

k6 is an open-source load testing tool from Grafana Labs. Tests are JavaScript; k6 runs them with many virtual users (VUs), each executing the default function in a loop. The test below ramps up to 20 users, holds, and ramps down, with thresholds that turn goals into pass or fail:

load.jsJavaScript
import http from "k6/http";
import { check, sleep } from "k6";

export const options = {
  stages: [
    { duration: "10s", target: 20 }, // ramp up to 20 virtual users
    { duration: "20s", target: 20 }, // hold
    { duration: "5s", target: 0 },   // ramp down
  ],
  thresholds: {
    http_req_failed: ["rate<0.01"],                      // under 1% errors
    "http_req_duration{endpoint:search}": ["p(95)<300"], // 95% of searches under 300 ms
  },
};

export default function () {
  const res = http.get("http://127.0.0.1:4300/search?q=miso", { tags: { endpoint: "search" } });
  check(res, { "status is 200": (r) => r.status === 200 });
  sleep(1); // think time between actions
}

The system under test is a small local server whose /search endpoint gets slower as more requests run at once, simulating a database under contention. k6 runs well from its official container image:

Shell
docker run --rm --network host -v "$PWD:/scripts" grafana/k6 run /scripts/load.js

At 20 users (k6 2.3):

Text
  █ THRESHOLDS

    http_req_duration{endpoint:search}
    ✓ 'p(95)<300' p(95)=65.62ms

    http_req_failed
    ✓ 'rate<0.01' rate=0.00%

  █ TOTAL RESULTS

    checks_succeeded...: 100.00% 541 out of 541
    http_req_duration..: avg=40.67ms min=34.65ms med=35.76ms max=81.41ms p(90)=51.47ms p(95)=65.62ms
    http_reqs..........: 541   15.124421/s

Both thresholds pass: p95 latency is 66 ms against a 300 ms goal, with no errors.

A stress test: where it breaks

The same script with the target raised to 200 users is a stress test:

Text
  █ THRESHOLDS
    ✗ 'p(95)<300' p(95)=2.06s
    ✓ 'rate<0.01' rate=0.00%

    http_req_duration..............: avg=1.64s min=34.76ms med=2.02s max=2.07s p(90)=2.06s p(95)=2.06s

level=error msg="thresholds on metrics 'http_req_duration{endpoint:search}' have been crossed"

Notice what the numbers say. Nothing failed: the error rate is still 0%. A test that only checked status codes would call this a success. But p95 latency went from 66 ms to over two seconds, and k6 exits with a non-zero status because the latency threshold was crossed, which fails a CI job. Users would experience a site that "works" but is unusable.

The next step is diagnosis, not more load: look at server metrics during the run to find the saturated resource (here, the simulated database contention), fix it (an index, a cache, a connection pool limit), and run the same test again to compare.

Common bottlenecks

When a stress test reveals a slowdown, the cause is usually one of a familiar handful:

  • N+1 queries: loading a list, then querying the database once per item. Load related data in one query.
  • Missing indexes: a query that scans a whole table, fast in testing and slow with production data.
  • Unbounded results: endpoints that return every row; add pagination and limits.
  • Slow external calls in the request path: move them to background jobs, add timeouts, and cache results where possible.
  • Lock contention: many requests waiting on the same row, table, or mutex.
  • Large payloads: oversized images, JSON, or JavaScript bundles.

Each of these shows up as rising latency long before errors appear, which is why thresholds on percentiles matter.

Reliability: soak and failure testing

Performance is about speed under load; reliability is about staying correct and available over time and through failures.

  • Soak tests run normal load for hours. Watch memory, file handles, connection counts, and latency trends; a slow upward line means a leak that will eventually crash the service.
  • Failure testing checks behavior when dependencies fail: kill a database replica, add network latency, make an external API time out. Does the application degrade gracefully, retry sensibly, and recover? This practice, done carefully and deliberately in controlled environments, is often called chaos engineering.
  • Timeouts and limits deserve explicit tests: every network call should have a timeout, and every queue a bound.

Benchmarks: measuring code, not systems

Load tests measure a whole system. Benchmarks measure small pieces of code, to compare implementations. Here, finding an ID among 10,000 with an array versus a Set, using tinybench (the library underneath Vitest's benchmarking) on Node.js:

lookup-bench.mjsJavaScript
import { Bench } from "tinybench";

const ids = Array.from({ length: 10_000 }, (_, i) => `class-${i}`);
const asSet = new Set(ids);
const wanted = "class-9999";

const bench = new Bench({ name: "find a class id among 10,000", time: 500 });
bench
  .add("Array.includes", () => ids.includes(wanted))
  .add("Set.has", () => asSet.has(wanted));

await bench.run();
console.table(bench.table());
Text
│ Task name        │ Latency avg (ns) │ Latency med (ns) │ Throughput avg (ops/s) │ Samples  │
│ 'Array.includes' │ '20243 ± 0.33%'  │ '18976 ± 60.00'  │ '50814 ± 0.15%'        │ 24700    │
│ 'Set.has'        │ '46.09 ± 0.09%'  │ '41.00 ± 1.00'   │ '22339325 ± 0.01%'     │ 10847471 │

The Set lookup takes about 46 nanoseconds against about 20 microseconds for the array, roughly 400 times faster here, because a Set doesn't scan every element. In Rust, the Criterion crate is the standard tool for the same kind of statistically careful comparison.

Benchmark wisely:

  • Benchmark realistic inputs and sizes; with ten elements the difference is irrelevant.
  • Run on a quiet machine, repeat, and look at variation (the ± figures), not one number.
  • Beware the compiler or JIT optimizing away code whose result isn't used.
  • Optimize what profiling shows is slow, not what you guess. Most code isn't the bottleneck.

Performance budgets in CI

Full load tests are slow and need a realistic environment, so most teams run them on a schedule or before releases. Lighter checks can run on every pull request:

  • a short k6 smoke test with thresholds against a preview environment;
  • web performance budgets with Lighthouse CI (lesson 12), such as maximum bundle size or Largest Contentful Paint;
  • benchmark comparisons for performance-critical code, failing on large regressions.

Common mistakes and troubleshooting

  • Reporting averages only. Use p95 and p99.
  • No goals. Define thresholds before testing.
  • Testing on unrealistic environments or data. Results won't predict production.
  • Load generator on the same machine as the system. They compete for resources.
  • Calling a test passed because there were no errors. Check latency too, as the stress test shows.
  • Load testing systems you don't own. Get explicit written permission, and coordinate with operators and providers.
  • k6 reports connection errors immediately. Check the target URL from the load generator's network; with Docker, use --network host or the container network name.

Practical exercise: find the breaking point

  1. Start a small local service with one fast and one slower endpoint (or use your own app's staging environment).
  2. Write a k6 script with thresholds for error rate and p95 latency.
  3. Run an average-load test, then a stress test at ten times the load, and record p95, throughput, and error rate.
  4. While the stress test runs, watch the server's CPU and memory. Which resource saturates first?
  5. Make one improvement and rerun the same test to compare.
  6. Benchmark two implementations of a hot function at realistic input sizes.

Key takeaways

  • Measure latency percentiles, throughput, error rate, and resource saturation against goals set in advance.
  • Smoke, average-load, stress, spike, soak, and breakpoint tests answer different questions.
  • Realistic environments and data make results meaningful.
  • k6 thresholds turn goals into pass or fail; a test with no errors can still fail on latency.
  • Benchmarks compare code at realistic sizes; profile before optimizing.

References

What's next

Fast for everyone means usable by everyone. Accessibility, Cross-Browser, and Cross-Platform Testing covers testing for people, browsers, and devices beyond your own.

See every lesson in Software Testing & Quality Engineering: From Fundamentals to Production-Ready Software