Advanced
Searching inHow-to guides
How to search
  • Type the task in your own words (find port, open firewall, disk full) or paste an error message in quotes.
  • Choose "Quick answer" to see only the commands, or an area to stay in one field.
  • "two words" finds the exact phrase.
  • Plain words find names, texts and examples.
  • ↑ ↓ to move · Enter to open · Esc to close · / to search
Try:

How-to 181Observability · k6

How to load test an API with k6

"It worked with 3 testers" says nothing about 300 real users. A load test sends many requests on purpose and measures response times and errors, so you find the limit before your customers do. k6 writes tests as small JavaScript files, ramps virtual users up and down, and fails with an exit code when your goals (thresholds) are missed — perfect for CI. This how-to writes a test, runs smoke and load tests, and reads the result.

  • 5 Lessons
  • 4 Commands

$ run as a normal user# run as root (or with sudo)

181.1

The quick answer

load.js
import http from 'k6/http';
import { check, sleep } from 'k6';
 
export const options = {
  stages: [
    { duration: '1m', target: 20 },
    { duration: '3m', target: 20 },
    { duration: '1m', target: 0 },
  ],
  thresholds: {
    http_req_failed: ['rate<0.01'],
    http_req_duration: ['p(95)<500'],
  },
};
 
export default function () {
  const res = http.get('https://api.example.com/products');
  check(res, { 'status is 200': (r) => r.status === 200 });
  sleep(1);
}
k6 run load.js

Commands in this lesson

181.2

Step by step

  1. Test a copy, not production — a staging system of the same size, or production only in a planned window and with the team informed.
  2. Smoke test first — 1 user for 30 seconds proves the script works:
k6 run --vus 1 --duration 30s load.js
  1. Load test (quick answer) — ramp to the normal peak (20 users), hold, ramp down. Each virtual user runs the default function again and again; sleep(1) acts like a person thinking.
  2. Thresholds are the goal — fewer than 1 % failed requests and 95 % of requests under 500 ms. If a threshold fails, k6 marks it with ✗ and exits with code 99, so CI fails.
  3. Real requests — log in, send JSON, use a token from the environment (never in the file):
post example
const params = { headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${__ENV.TOKEN}` } };
const res = http.post('https://api.example.com/orders', JSON.stringify({ sku: 'A-100', qty: 1 }), params);
k6 run -e TOKEN="$(cat /run/secrets/test-token)" load.js
  1. Other test types — stress (ramp past the peak to find the breaking point), spike (0 → 200 users in 10 s), soak (normal load for 2–4 hours to find memory leaks).
  2. Read the summary — look at http_req_duration (avg, p(90), p(95)), http_req_failed and iterations. Watch the server dashboards at the same time: CPU, database connections, error logs.
  3. Store results over time — send metrics to Prometheus and compare runs in Grafana:
K6_PROMETHEUS_RW_SERVER_URL=http://prometheus.example.com:9090/api/v1/write k6 run -o experimental-prometheus-rw load.js

Commands in this lesson

181.3

Check that it worked

The run ends with all thresholds marked ✓ and exit code 0 (echo $?); the request count matches the plan (about 20 users × 1 request per second); the server dashboards show the load at the same time.

Commands in this lesson

181.4

Common problems

ProblemCauseFix
Many 429 responsesRate limit or WAF blocks the test.Allow the test machine's IP in staging; or test behind the limiter on purpose.
The load machine is at 100 % CPUThe client is the bottleneck, not the API.Bigger machine, fewer checks per request, or distributed k6.
dial tcp: too many open filesFile descriptor limit.ulimit -n 65535 before the run.
Results look too goodResponses served from a cache or CDN.Vary URLs/parameters; test the origin as well.
CI is green though times were badNo thresholds set.Add thresholds; k6 then exits with code 99.
Test data fills the databaseEvery iteration creates orders.Use a test tenant; clean up in teardown().

181.5

Go further

1Why does a k6 test need thresholds?

Thresholds turn the goal into pass or fail: when one fails, k6 exits with a non-zero code and the pipeline stops.

2What is the difference between a load test and a stress test?

A load test checks the normal peak; a stress test goes past it on purpose to find where the system breaks.

All commands in this chapter