Grafana k6: write a load test and understand its results
Install k6, write HTTP scripts, distinguish VUs from request rates, set check and latency thresholds, model a guarded test journey, and connect results to application telemetry.
Grafana k6 defines load tests in code and reports the work they generate. Its engine is written in Go, while scripts use JavaScript or, in modern versions, TypeScript. The scripts do not run in Node.js. How much load a generator can sustain depends on the script, protocol, and available resources; a particular VU count is not a portable performance guarantee.
A useful first test also needs clear definitions. By default, an HTTP 302 can count as an expected response while failing a custom “status is 200” check. A VU target does not specify requests per second. Those distinctions matter before a test becomes a CI gate.
This guide follows official documentation; we did not run a k6 load test or performance benchmark. The API paths and data must be implemented by your project. Grafana Labs acquired k6 in 2021; its results can be visualized in Grafana through a suitable backend.
Why use k6?
Scripts can go into Git, receive code review, and run in CI. Those are useful working practices, but not exclusive k6 capabilities: JMeter supports non-GUI execution, and Locust is also script-driven. Compare languages, protocols, execution models, and maintenance rather than assuming every alternative requires manual clicking.
k6 has its own JS/TS runtime. A package that depends on Node.js built-in APIs cannot simply be copied into it. The examples here generate protocol-level HTTP requests; they do not execute a page's JavaScript or render it. Browser tests need the appropriate module and a separate resource budget.
Install and run it
Save the next example as script.js. Before running, export BASE_URL as the base address of your authorized test API, without a query string or fragment. A name such as api.example.com is an illustration, not a public load-testing service.
# Install on macOS
brew install k6
# Run locally after preparing script.js and exporting BASE_URL
k6 run script.js
# Or use Docker: forward exported BASE_URL and read the script from stdin
docker run --rm -i -e BASE_URL grafana/k6:2.3.0 run - < script.js
The Docker example pins the verified 2.3.0 tag. A tag does not guarantee immutable image content; use a verified digest when that is required. -i keeps stdin open for the script. Local files or relative modules need appropriate mounts as well. Homebrew may install another version, so check k6 version. Installation · Running scripts
Write the first script
import http from 'k6/http';
import { check, sleep } from 'k6';
if (!__ENV.BASE_URL) throw new Error('Set BASE_URL to an authorized test API');
const baseUrl = __ENV.BASE_URL.replace(/\/+$/, '');
export const options = {
vus: 20, // 20 virtual users, not 20 RPS
duration: '30s', // Duration of the constant-VU scenario
thresholds: {
http_req_failed: ['rate<0.01'],
http_req_duration: ['p(95)<500'],
checks: ['rate>0.99'],
},
};
export default function () {
const res = http.get(`${baseUrl}/users`);
check(res, {
'status is 200': (r) => r.status === 200,
'duration is below 500ms': (r) => r.timings.duration < 500,
});
sleep(1);
}
vus and duration are shortcuts for a constant-VU scenario. Each VU repeats the request and sleep; that does not promise a fixed RPS. End-of-test timing also depends on graceful-stop settings. Your project must provide /users and the expected 200 response.
A failed check records a result but does not, by itself, make the process exit unsuccessfully. Thresholds provide the CI pass/fail gate. Here, rate<0.01 means strictly fewer than 1% failed HTTP requests, p(95)<500 means the duration metric's P95 must be strictly below 500 ms, and checks: rate>0.99 requires strictly more than 99% of all executed checks to pass. It combines the two checks; it does not enforce a separate 99% target for each. Use suitable check or request tags when individual conditions need their own thresholds.
http_req_failed follows the expected-response rule, which defaults to HTTP 200–399. That differs from the custom status === 200 check. An unfiltered http_req_duration threshold includes all samples of that metric, not only successful requests or one endpoint. P95 is a request-duration quantile, not a percentage of users. The duration adds sending, waiting, and receiving time; it excludes the initial DNS lookup and connection setup.
These values illustrate syntax, not a universal SLO. Use an owned or authorized isolated environment, begin with a small VU count, and check data and generator headroom. A normal threshold is not an immediate stop switch: early termination needs explicit settings such as abortOnFail, while resource and cost limits need the corresponding measurements or external controls. Order tests belong in test-order and payment-sandbox workflows. Checks and thresholds · Expected responses
Change the VU curve
stages changes the VU population over time. This is an alternative options configuration: replace the earlier one rather than declaring it twice or combining the constant-scenario vus/duration shortcuts with it.
export const options = {
stages: [
{ duration: '2m', target: 100 }, // Ramp to 100 VUs over 2 minutes
{ duration: '5m', target: 100 }, // Hold 100 VUs for 5 minutes
{ duration: '2m', target: 0 }, // Ramp down to 0 VUs over 2 minutes
],
};
The target is VUs, not requests per second. Response time, requests per iteration, and think time can change throughput even when the VU count is unchanged. Stages can express stepped, spike, and soak patterns. This replacement also omits the earlier thresholds; add back the ones needed for the same test objective. Ramping VUs
Model a journey without sending invalid follow-up requests
A journey can exercise a cross-endpoint business process; an isolated API test is still useful for capacity or regression work. This separate script assumes an example project contract: login accepts JSON user/pass and returns HTTP 200 with a string token; products returns an array containing sku; creating a test order returns 201 with a string id. k6 does not supply these endpoints. Adapt each path and field to the application.
In addition to BASE_URL, provide TEST_USER, TEST_PASS, and TEST_SKU. Forward them explicitly when using Docker. The example runs one journey; before scaling it, prepare suitable isolated accounts, SKUs, and test data.
import http from 'k6/http';
import { check, sleep } from 'k6';
const required = ['BASE_URL', 'TEST_USER', 'TEST_PASS', 'TEST_SKU'];
if (required.some((key) => !__ENV[key])) {
throw new Error('Set BASE_URL, TEST_USER, TEST_PASS, and TEST_SKU for your test API');
}
const baseUrl = __ENV.BASE_URL.replace(/\/+$/, '');
export const options = { vus: 1, iterations: 1, thresholds: { checks: ['rate==1'] } };
function jsonOrNull(response) {
try { return response.json(); } catch (_) { return null; }
}
export default function () {
const login = http.post(`${baseUrl}/login`, JSON.stringify({
user: __ENV.TEST_USER, pass: __ENV.TEST_PASS,
}), { headers: { 'Content-Type': 'application/json' } });
const loginBody = jsonOrNull(login);
const token = typeof loginBody?.token === 'string' ? loginBody.token : '';
if (!check(login, { 'login returns 200 and a token': (r) => r.status === 200 && token.length > 0 })) {
sleep(1);
return;
}
const params = { headers: {
Authorization: `Bearer ${token}`, 'Content-Type': 'application/json',
} };
const products = http.get(`${baseUrl}/products`, params);
const catalog = jsonOrNull(products);
if (!check(products, { 'catalog includes the test SKU': (r) => r.status === 200
&& Array.isArray(catalog) && catalog.some((item) => item?.sku === __ENV.TEST_SKU) })) {
sleep(1);
return;
}
const order = http.post(`${baseUrl}/orders`, JSON.stringify({
sku: __ENV.TEST_SKU, qty: 1,
}), params);
const created = jsonOrNull(order);
check(order, { 'test order was created': (r) => r.status === 201
&& typeof created?.id === 'string' && created.id.length > 0 });
sleep(2);
}
jsonOrNull lets a non-JSON response fail a check instead of throwing during token parsing. If authentication or the catalog check fails, the script returns before creating a dependent order. It also checks the order response. The checks threshold requires every executed check to pass; it does not define business correctness, test-data cleanup, or a throughput objective for you.
Read the results by their population
Distinguish requests, iterations, and checks in the built-in metrics:
| Metric | Meaning |
|---|---|
http_req_duration |
Distribution of HTTP sending, waiting, and receiving time, excluding initial DNS/connection setup; P90/P95 describe request samples |
http_req_failed |
Failed-request fraction under the expected-response rules, not every possible business failure |
vus / iterations |
Current active VUs / cumulative iterations; a journey can make several requests or return early |
checks |
Pass fraction across executed checks; neither request count nor user count |
Configure an output and a compatible results backend. The currently documented experimental experimental-prometheus-rw output sends metrics to a configured Prometheus remote-write receiver. Grafana queries that storage backend; it is not a time-series store that accepts any arbitrary --out. Match receiver address, authentication, TLS, and version support. Built-in metrics · Prometheus remote write
Record each run's start and end, application version, and test identifier. Compare a latency increase with application logs and resource measurements in that window. To inspect server-side calls, instrument the tested application through a supported OpenTelemetry ingestion path in Guance, then examine the collected downstream spans. This is separate from exporting k6 results.
A k6 tag does not automatically become a log or span field. Carrying a test identifier requires an agreed request header and application recording. Trace correlation also needs appropriate context propagation, sampling, retention, and access. Missing traces cannot reconstruct the entire load run.
Common questions
How should I choose between k6, JMeter, and Locust? Compare script languages, protocols, and team experience. k6 has its own JS/TS runtime, Locust uses Python, and JMeter can run without its GUI. Evaluate generator performance on the same workload; no tool promises more VUs for every script.
Must every script call sleep? No. A user-session model may need think time. An arrival-rate executor already controls iteration starts, so usually avoid an extra sleep at the end to regulate that rate. Iterations per second are not HTTP RPS when one iteration contains several requests. VUs do not imply fixed RPS, and the generator itself can become a bottleneck.
Which environment should I test? Prefer a staging environment that resembles production. Testing production needs a deliberate risk assessment, load limits, and a way to stop. Differences in staging resources, data, or dependencies also mean its results are not a production-capacity guarantee.
Official references
Technical references checked November 5, 2026. The example image is 2.3.0; recheck runtime behavior and output support when changing versions.
Continue reading
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan
