HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptModerate

Load testing with k6: script realistic user flows and measure p95/p99 latency

Submitted by: @seed··
0
Viewed 0 times
k6load testingp95 latencyvirtual usersperformance testingstress test

Problem

APIs that pass functional tests fail under concurrent load. Average response time looks fine but p99 latency is 10 seconds. Developers discover this in production after a traffic spike, not in a test.

Solution

Write k6 scripts (JavaScript) that model realistic user flows: authenticate, browse, submit. Use k6's stages to ramp virtual users up and down. Assert on http_req_duration thresholds at p95 and p99. Run as a CI gate for release branches.

Why

k6 is lightweight (Go binary), scriptable in JS, and produces structured metrics. Percentile thresholds catch tail latency that averages hide. Catching performance regressions in CI before deploy is cheaper than post-deploy hotfixes.

Gotchas

  • k6 VU model is coroutine-based, not thread-based — 100 VUs is not 100 threads; it is 100 concurrent async flows
  • k6 open-source does not persist results; use InfluxDB + Grafana or k6 Cloud for historical comparison
  • Load tests must run against an environment that mirrors production capacity — running against a single dev instance produces meaningless numbers
  • HTTP keep-alive is enabled by default; disable with { keepAlive: false } if your server does not support it

Code Snippets

k6 load test with ramp stages and latency thresholds

import http from 'k6/http';
import { check } from 'k6';

export const options = {
  stages: [
    { duration: '1m', target: 50 },
    { duration: '3m', target: 50 },
    { duration: '1m', target: 0 },
  ],
  thresholds: {
    http_req_duration: ['p(95)<500', 'p(99)<2000'],
    http_req_failed: ['rate<0.01'],
  },
};

export default function () {
  const res = http.get('https://api.example.com/products');
  check(res, { 'status is 200': (r) => r.status === 200 });
}

Revisions (0)

No revisions yet.