Testing and QA · Intermediate · 22 min
Load test an API with k6
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · k6 2.4.0 · Python 3 (Ubuntu package)
You will install k6 2.4 on Ubuntu, write a load script with virtual users, checks, thresholds and custom metrics for a small local API, and watch the same script pass against a fast endpoint and fail against a slow one.
On this page
A load test answers a question unit tests cannot: what happens to response times and errors when many clients call the API at once. k6 is a load-testing tool from Grafana Labs. You write the traffic as a JavaScript file, and a single Go binary runs it with as many virtual users (VUs) as you ask for. Each VU runs your function in a loop, like one user who never gets bored.
In this tutorial you write a k6 script for a small product API that you run on your own machine. The script sends traffic, checks every response, and sets thresholds: pass/fail rules on latency and error rate that make k6 exit with an error code when they are broken. That exit code is what turns a load test into something a CI pipeline can act on.
Only load test what you own
A load test is deliberate heavy traffic. Aimed at someone else's service, it looks like a denial-of-service attack, it can take the service down for real users, and it may break the provider's terms or the law. Only load test systems you own or run, or ones whose owner has agreed in writing, and agree the time window with the people on call. Cloud and API-gateway bills often grow with request count, so a load test can also cost money. Everything here runs against 127.0.0.1.
Step 1 · Install k6 from Grafana's apt repository
k6 is not in Ubuntu's own archive. Grafana publishes a signed apt repository. Install the tools needed to add it, plus Python 3, which runs the practice API in the next step (Ubuntu Server already has it):
sudo apt-get update
sudo apt-get install -y ca-certificates curl gpg python3Add Grafana's signing key and the repository, then install k6:
curl -fsSL https://dl.k6.io/key.gpg | sudo gpg --dearmor --yes -o /usr/share/keyrings/k6-archive-keyring.gpg
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 k6The repository carries the newest release, so later sudo apt-get upgrade runs keep k6 up to date.
On an Arm server
Grafana's apt repository only carries amd64 builds. If dpkg --print-architecture prints arm64 (Graviton, Ampere and Raspberry Pi machines, for example), sudo apt-get install -y k6 reports Unable to locate package k6. Remove the repository you just added and install the release binary from GitHub instead, checking it against the published checksums:
sudo rm /etc/apt/sources.list.d/k6.list /usr/share/keyrings/k6-archive-keyring.gpg
sudo apt-get update
cd /tmp
curl -fsSLO https://github.com/grafana/k6/releases/download/v2.4.0/k6-v2.4.0-linux-arm64.tar.gz
curl -fsSLO https://github.com/grafana/k6/releases/download/v2.4.0/k6-v2.4.0-checksums.txt
grep " k6-v2.4.0-linux-arm64.tar.gz$" k6-v2.4.0-checksums.txt | sha256sum -c -
tar -xzf k6-v2.4.0-linux-arm64.tar.gz
sudo install -m 755 k6-v2.4.0-linux-arm64/k6 /usr/local/bin/k6
rm -rf k6-v2.4.0-linux-arm64 k6-v2.4.0-linux-arm64.tar.gz k6-v2.4.0-checksums.txt
cd ~A binary installed this way gets no apt updates. To upgrade, check the k6 releases page and repeat these commands with the new version number in place of 2.4.0.
If you used k6 1.x
k6 2.0 was a major release. The scripting API in this tutorial (k6/http, checks, thresholds, custom metrics, __ENV, handleSummary) works the same in both, but a few things changed for 1.x users:
- The end-of-test summary has three modes,
compact(the default),fullanddisabled.--summary-mode=legacyand--no-summaryare gone; use--summary-mode=disabledinstead of the latter. - The
externally-controlledexecutor andoptions.ext.loadimpactwere removed, andk6 loginbecamek6 cloud login.
Grafana still ships fixes for the 1.x line, but new work happens in 2.x. Read Grafana's "Migrate to k6 v2" guide before upgrading a shared suite.
Check it worked
k6 version
k6 version | grep -q "v2\."The first command prints something like k6 v2.4.0 (go1.x, linux/amd64). A later 2.x release is fine.
Step 2 · Run a practice API
You need an API to aim at. This one uses only Python's standard library. It serves 20 products, one product by ID, and a deliberately slow copy of the list that waits 350 ms before answering. The slow route stands in for an endpoint with an unindexed query or a slow upstream.
mkdir -p ~/k6-demo
cd ~/k6-demo
cat > api.py <<'PY'
import json
import random
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
PRODUCTS = [{"id": n, "name": f"Product {n}", "price": 500 + n * 25} for n in range(1, 21)]
class Handler(BaseHTTPRequestHandler):
def send_json(self, status, payload):
body = json.dumps(payload).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
if self.path == "/api/products":
time.sleep(random.uniform(0.005, 0.02))
return self.send_json(200, PRODUCTS)
if self.path == "/api/products-slow":
time.sleep(0.35)
return self.send_json(200, PRODUCTS)
if self.path.startswith("/api/products/"):
wanted = self.path.rsplit("/", 1)[1]
for product in PRODUCTS:
if str(product["id"]) == wanted:
return self.send_json(200, product)
return self.send_json(404, {"error": "no such product"})
self.send_json(404, {"error": "not found"})
def log_message(self, format, *args):
pass
server = ThreadingHTTPServer(("127.0.0.1", 8081), Handler)
server.daemon_threads = True
server.serve_forever()
PYStart it in your second terminal, from ~/k6-demo, and leave it running:
python3 api.pyIt prints nothing while it runs, because request logging is switched off. Run everything else in your first terminal.
Check it worked
curl -s http://127.0.0.1:8081/api/products/3
curl -s http://127.0.0.1:8081/api/products/3 | grep -q '"name": "Product 3"'The first command prints {"id": 3, "name": "Product 3", "price": 575}.
Step 3 · Write a first script with virtual users and checks
A k6 script has two parts. Code at the top level runs once per VU when it starts (imports, options). The exported default function is the work each VU repeats until the run ends. options sets how many VUs run and for how long.
cd ~/k6-demo
cat > load-test.js <<'JS'
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
vus: 10,
duration: '15s',
};
export default function () {
const res = http.get('http://127.0.0.1:8081/api/products');
check(res, {
'status is 200': (r) => r.status === 200,
'returns 20 products': (r) => r.json().length === 20,
});
sleep(1);
}
JS
k6 run load-test.jscheck records a pass or fail for each condition; it does not stop the VU. sleep(1) is think time: a real client pauses between calls, and without it ten VUs would send requests as fast as the machine allows, which measures something different. With ten VUs and a one-second pause you get roughly ten requests a second.
While it runs, k6 shows a progress bar. At the end it prints the summary: your checks with a pass percentage, then built-in metrics such as http_req_duration (with avg, min, med, max, p(90) and p(95)), http_req_failed, http_reqs and iterations.
Check it worked
The checks section shows both checks at 100%, http_req_failed is 0.00%, and http_reqs is about 150 (10 VUs × 15 seconds). If every request fails, the practice API is not running in the other terminal.
Step 4 · Add thresholds that fail the run
Numbers in a summary are easy to ignore. Thresholds turn them into rules. Add three:
http_req_duration: ['p(95)<200']: 95% of requests finish in under 200 ms. Percentiles matter more than the average, because the average hides the slow tail that users actually notice.http_req_failed: ['rate<0.01']: fewer than 1% of requests fail. k6 counts a status of 400 or above, or no response, as failed.checks: ['rate>0.99']: more than 99% of checks pass. A failed check on its own never changes the result of a run; this threshold is what makes it count.
Replace the script with this version:
cd ~/k6-demo
cat > load-test.js <<'JS'
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
vus: 10,
duration: '15s',
thresholds: {
http_req_duration: ['p(95)<200'],
http_req_failed: ['rate<0.01'],
checks: ['rate>0.99'],
},
};
export default function () {
const res = http.get('http://127.0.0.1:8081/api/products');
check(res, {
'status is 200': (r) => r.status === 200,
'returns 20 products': (r) => r.json().length === 20,
});
sleep(1);
}
JS
k6 run load-test.js && echo "thresholds passed"Pick threshold numbers from what your users need and what the service does today, not from this tutorial. A good starting point is your current p95 plus some headroom, tightened as you improve things.
Check it worked
The summary now has a thresholds section with a tick next to each rule, and the last line is thresholds passed. That line only prints when k6 exits with code 0.
Step 5 · Add custom metrics and environment variables
Two things make a script reusable. First, read the target from the environment, so the same file runs against your laptop, a staging server or a CI service without edits. k6 exposes environment variables as __ENV, and k6 run -e NAME=value sets them for one run. Never put API keys in the script: read them from __ENV too, from a variable you set in your shell or CI secrets.
Second, record what matters to you. Built-in metrics cover all requests together. A custom Trend stores values and reports percentiles; a Counter adds up a number. Here a Trend times product-detail requests on their own, a Counter counts how many products were viewed, and a threshold applies to the custom trend.
The detail URL changes with every ID. The name tag groups those URLs under one label so the results do not split into twenty separate entries.
cd ~/k6-demo
cat > load-test.js <<'JS'
import http from 'k6/http';
import { check, sleep } from 'k6';
import { Counter, Trend } from 'k6/metrics';
const BASE_URL = __ENV.BASE_URL || 'http://127.0.0.1:8081';
const PRODUCTS_PATH = __ENV.PRODUCTS_PATH || '/api/products';
const detailDuration = new Trend('product_detail_duration', true);
const productsViewed = new Counter('products_viewed');
export const options = {
vus: 10,
duration: __ENV.DURATION || '15s',
thresholds: {
http_req_duration: ['p(95)<200'],
http_req_failed: ['rate<0.01'],
checks: ['rate>0.99'],
product_detail_duration: ['p(95)<150'],
},
};
export default function () {
const list = http.get(`${BASE_URL}${PRODUCTS_PATH}`);
check(list, {
'list status is 200': (r) => r.status === 200,
'list has 20 products': (r) => r.json().length === 20,
});
const id = Math.floor(Math.random() * 20) + 1;
const detail = http.get(`${BASE_URL}/api/products/${id}`, {
tags: { name: 'GET /api/products/:id' },
});
check(detail, {
'detail status is 200': (r) => r.status === 200,
'detail has the right id': (r) => r.json().id === id,
});
detailDuration.add(detail.timings.duration);
productsViewed.add(1);
sleep(1);
}
JS
k6 run -e BASE_URL=http://127.0.0.1:8081 load-test.jsThe true passed to Trend marks its values as times, so the summary shows them in milliseconds. detail.timings.duration is the time from sending the request to receiving the whole response, the same value k6 uses for http_req_duration.
Check it worked
The summary lists product_detail_duration with its own percentiles and a ticked threshold, and products_viewed with a count close to http_reqs divided by two, since each iteration makes two requests.
Step 6 · Watch the thresholds fail on a slow endpoint
A threshold is only useful if it fails when things get worse. Point the list request at the slow route. Nothing in the script changes; only an environment variable does:
cd ~/k6-demo
k6 run -e PRODUCTS_PATH=/api/products-slow load-test.js || echo "k6 exited with code $?"Half the requests now take at least 350 ms, so the 95th percentile of http_req_duration lands well above 200 ms. The detail requests are still fast, so product_detail_duration stays green. That is the point of a threshold on a custom metric: it tells you which part got slow.
When any threshold fails, k6 exits with code 99. A CI job treats any non-zero code as a failure, so a pipeline step that runs k6 run load-test.js stops a slow change from shipping without any extra logic.
Check it worked
In the thresholds section, http_req_duration has a cross next to p(95)<200 and the other rules keep their ticks. k6 reports that thresholds were crossed, and the last line is k6 exited with code 99. All checks still pass: the slow route returns correct data, just late. Checks test correctness; thresholds test speed and reliability.
Step 7 · Save a summary file for later
The printed summary disappears with the terminal. Export a handleSummary function and k6 calls it at the end of the run with every metric, and writes whatever it returns. Keys are file paths, or stdout. Defining it replaces the default printed summary, so put it in a separate entry file and keep load-test.js as it is:
cd ~/k6-demo
cat > report-run.js <<'JS'
import run, { options as baseOptions } from './load-test.js';
export const options = baseOptions;
export default run;
export function handleSummary(data) {
const allOk = Object.values(data.metrics).every((metric) =>
Object.values(metric.thresholds || {}).every((t) => t.ok),
);
const report = {
p95_ms: data.metrics.http_req_duration.values['p(95)'],
failed_rate: data.metrics.http_req_failed.values.rate,
products_viewed: data.metrics.products_viewed.values.count,
thresholds_ok: allOk,
};
return {
'summary.json': JSON.stringify(report, null, 2) + '\n',
stdout: `p95 ${report.p95_ms.toFixed(1)} ms, thresholds ok: ${allOk}\n`,
};
}
JS
k6 run report-run.js
cat summary.jsonKeep these files with a date, or store them as CI artefacts, and you can compare runs over weeks. If you run load tests from a laptop on prepaid mobile data, common in Lagos, Nairobi or Accra, note that every request and response crosses your connection: start with low VU counts, or run k6 from a server in the same region as the API, which keeps the traffic off your mobile data and stops the network from distorting the latency figures (check your provider's data-transfer pricing first).
Check it worked
cd ~/k6-demo
grep -q '"thresholds_ok": true' summary.jsonThe run prints one line such as p95 18.4 ms, thresholds ok: true in place of the full summary, and summary.json shows the same p95, a failed_rate of 0, the products_viewed count and "thresholds_ok": true.
Step 8 · Clean up
Stop the practice API with Ctrl+C in the second terminal, then remove the demo folder. k6 stays installed for the next tutorials.
cd ~
rm -rf ~/k6-demoTo remove k6 as well, run sudo apt-get remove k6, then delete /etc/apt/sources.list.d/k6.list and /usr/share/keyrings/k6-archive-keyring.gpg. If you installed the release binary on an Arm server, run sudo rm /usr/local/bin/k6 instead.
Check it worked
ls ~/k6-demo reports that the folder does not exist, and curl http://127.0.0.1:8081/api/products fails to connect.
Next steps
- Ramp traffic up and down, and send requests at a fixed rate rather than per user: model realistic traffic with k6 scenarios and arrival rates.
- Learn what p95, throughput and saturation tell you, and how to spot the point where a service tips over: read load test results.
- Swap the practice API for a real one you own: build a REST API with FastAPI, then point
BASE_URLat it.
Related tutorials
- Write unit tests that stay useful as the code changesYou will replace a brittle pytest suite with behaviour tests that catch a real boundary bug and stay green when the code under them is rewritten.
- Write property-based tests in TypeScript with fast-checkYou will use fast-check and Vitest to find a rounding bug in a TypeScript money module, replay the failure from its seed, fix it, and model-test a shopping cart with generated command sequences.
- Write negative tests for an API: bad input, auth and limitsYou will build a pytest and httpx suite that attacks a small FastAPI ordering API with missing and extra fields, wrong types, boundary values, long and multilingual text, bad tokens, another user's data, rate limits and reused idempotency keys, and proves every error comes back in one RFC 9457 format.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials