Home › Guides › Grafana k6 tutorial

Grafana k6 Tutorial: Your First Load Test

Ten virtual users hit a website for two minutes, and you see every response time, error and check. This guide follows my video step by step. You install k6 on Ubuntu, write the test, run it, and read the results line by line. Then you make a threshold fail on purpose, and stream the results to Grafana Cloud with one command.

What you need

Recorded with k6 v2.4 and the Grafana Cloud free plan.

What is a load test?

A load test sends many requests to a website at the same time and measures how it responds. k6 is an open source load testing tool from Grafana Labs. You write the test in JavaScript.

script.jsyour test, in JavaScript→ Virtual userseach one runs the function in a loop→ Resultsp(95), errors, checks

k6 starts virtual users (VUs). Each one runs your test function in a loop, like a real visitor clicking around. k6 measures every request they make.

What makes it a test, not just a benchmark, is thresholds. A threshold is a pass or fail rule, for example "95% of requests faster than half a second". If a threshold fails, k6 fails. So it can stop a bad release in your CI pipeline.

The same script can run different kinds of tests:

TestWhat it checks
LoadNormal traffic. This is the one we run here.
StressPushes past normal traffic to find the breaking point.
SpikeA sudden jump, like a sale starting.
SoakRuns for hours, to find slow memory leaks.

Only load test sites you own, or have permission to test. To a website, a load test looks like an attack. This guide uses QuickPizza (quickpizza.grafana.com), a demo app that Grafana runs for exactly this kind of practice.

Step 1: install k6 on Ubuntu

k6 comes from Grafana's package repository. These commands add the signing key and the repository, then install k6. Paste them all at once.

sudo gpg -k
sudo gpg --no-default-keyring --keyring /usr/share/keyrings/k6-archive-keyring.gpg --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys C5AD17C747E3415A3642D57D77C6C491D6AC1D69
echo "deb [signed-by=/usr/share/keyrings/k6-archive-keyring.gpg] https://dl.k6.io/deb stable main" | sudo tee /etc/apt/sources.list.d/k6.list
sudo apt-get update
sudo apt-get install -y k6

ARM machine? The apt repository is amd64 only. On an ARM server, for example a Raspberry Pi, download the linux-arm64 build from github.com/grafana/k6/releases.

Step 2: check the version

k6 version

It prints the version number, so the install worked. In the video it shows k6 v2.4.0. A newer version is fine.

Step 3: write the test script

Create a file called script.js:

nano script.js

Paste this:

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

export const options = {
  stages: [
    { duration: '30s', target: 10 },  // ramp up to 10 users
    { duration: '1m', target: 10 },   // stay at 10 users
    { duration: '30s', target: 0 },   // ramp down
  ],
  thresholds: {
    http_req_failed: ['rate<0.01'],    // less than 1% errors
    http_req_duration: ['p(95)<500'],  // 95% of requests under 500 ms
  },
};

export default function () {
  const res = http.get('https://quickpizza.grafana.com/');
  check(res, { 'status is 200': (r) => r.status === 200 });
  sleep(1);
}

Save with Ctrl+O and Enter, and exit with Ctrl+X.

The imports

options.stages: the load shape

Two minutes in total. Ramping up slowly shows you where things start to slow down.

options.thresholds: the pass or fail rules

The default function: what every virtual user does

Each virtual user runs this function over and over:

  1. http.get(...) gets the page.
  2. check(...) checks that the status is 200. A failed check is counted in the results, but it does not stop the test.
  3. sleep(1) waits one second, like a person reading the page.

How much traffic is that?

Each virtual user makes one request, then sleeps a second. So ten users make roughly ten requests per second. Want more traffic? Raise the target in the stages, or shorten the sleep.

Step 4: run the test

k6 run script.js

The progress bar shows the virtual users going up, holding at ten, and going down. This takes two minutes. Then k6 prints the summary.

Step 5: read the results

This is the summary from my run, slightly trimmed. Your numbers will differ.

█ THRESHOLDS

  http_req_duration
  ✓ 'p(95)<500' p(95)=145.39ms

  http_req_failed
  ✓ 'rate<0.01' rate=0.00%

█ TOTAL RESULTS

  checks_total.......: 802     6.672208/s
  checks_succeeded...: 100.00% 802 out of 802
  checks_failed......: 0.00%   0 out of 802

  ✓ status is 200

  HTTP
  http_req_duration..............: avg=141.69ms min=138.84ms med=141.28ms max=345.86ms p(90)=143.7ms p(95)=145.39ms
  http_req_failed................: 0.00%  0 out of 802
  http_reqs......................: 802    6.672208/s

  EXECUTION
  iterations.....................: 802    6.672208/s
  vus_max........................: 10     min=10 max=10

Thresholds

At the top. Both have a green check mark. The 95th percentile was well under 500 milliseconds, and no request failed.

Checks

100% of the responses had status 200 (802 out of 802).

http_req_duration

This is the response time. It has six values:

Watch the percentiles, not the average. p(95) means 95 out of 100 requests were at least this fast. The slow tail is what your users notice.

http_reqs and iterations

http_reqs is how many requests the site handled, in total and per second. iterations is how many times the virtual users ran the whole function. Here each iteration makes one request, so the two numbers are the same.

Tip: why 6.7 per second, not 10? Ten users only run during the middle minute. During the ramp up and ramp down there are fewer, so the average over the whole two minutes is lower.

Step 6: make a threshold fail on purpose

Change the response time threshold from 500 to 100 milliseconds. Then run a short test: five users for twenty seconds, set right on the command line.

sed -i 's/p(95)<500/p(95)<100/' script.js
k6 run --vus 5 --duration 20s script.js

The --vus and --duration flags override the stages in the script. You can also edit the line in nano instead of using sed.

The response time threshold now has a red cross, and k6 ends with an error:

http_req_duration
✗ 'p(95)<100' p(95)=149.76ms
...
ERRO[0021] thresholds on metrics 'http_req_duration' have been crossed

Check the exit code:

echo $?
99

Exit code 99 means a threshold failed. A non-zero exit code is what stops a CI pipeline. Now change the threshold back to 500:

sed -i 's/p(95)<100/p(95)<500/' script.js

Step 7: send the results to Grafana Cloud

The terminal summary disappears when you close it. To keep results and compare runs, send them to Grafana Cloud. The free plan includes k6.

Create a stack token

  1. In Grafana Cloud, open Testing & synthetics → Performance → Configuration.
  2. Open the Stack token tab and click Create token.
  3. Name it after your server, and click Create new token.
  4. Copy the token now. Grafana shows it only once.

Treat the token like a password. Anyone who has it can run tests and send results to your stack. Don't paste it into a shared script or a Git repository.

Log in from the server

Replace YOUR_TOKEN with the token, and YOUR_STACK with your stack name. The stack name is the first part of your Grafana Cloud address: for mystack.grafana.net it is mystack.

k6 cloud login -t YOUR_TOKEN --stack YOUR_STACK

k6 saves the login, so you only do this once on each machine.

Run the test and stream the results

k6 cloud run --local-execution script.js

The test still runs on your own server, but every result streams to Grafana Cloud. At the start, k6 prints a link to the result page. Open it while the test runs, or after.

Step 8: the results in Grafana Cloud

The main graph shows the virtual users, the request rate and the response time together, over the whole test. You see exactly when the response time moved as users were added. The header shows the run summary, for example 10 VUs, 2 min and Local execution.

Below the graph are the tabs. The ones used in the video:

Every run is saved here, so you can compare today's test with last week's. The Compare box at the top of the result page picks an earlier run of the same script.

Running the virtual users in the cloud

Without --local-execution, the same command works differently:

k6 cloud run script.js

Now k6 starts the virtual users on Grafana's servers instead, in a load zone you choose. That's how you test from outside your own network. The video only shows the command, it doesn't run it.

Tip: cloud execution uses your plan's allowance of virtual user hours (the VUh number on the result page). Check the limits of your plan before you run big tests in the cloud.

If the cloud login fails

If k6 cloud says you're not authorized, run k6 cloud login again with a fresh token. Then check that the stack name matches your Grafana Cloud address.

k6 cloud login -t YOUR_NEW_TOKEN --stack YOUR_STACK

In the video I also run k6 cloud login -s, which shows the login k6 has saved, so you can see which stack it points to.

All the commands

CommandWhat it does
k6 versionPrints the installed version.
k6 run script.jsRuns the test on this machine and prints the summary.
k6 run --vus 5 --duration 20s script.jsA short test. The flags override the stages.
k6 cloud login -t YOUR_TOKEN --stack YOUR_STACKSaves your Grafana Cloud login.
k6 cloud run --local-execution script.jsRuns here, results in Grafana Cloud.
k6 cloud run script.jsRuns on Grafana's load generators.

Watch the video

The whole walkthrough in six minutes, from a fresh Ubuntu machine to the result page in Grafana Cloud.

Related

Need help with load testing or monitoring?

One script against a demo app is the start. Real load tests need the right user journeys, sensible thresholds, and a place in your CI pipeline. Then you need monitoring that tells you why things slowed down. I'm a Grafana Champion, and I set up load tests, dashboards and alerts through KorFlux. Tell me what you run and I'll tell you how I'd test it.