Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 36 ยท Projects and Practice

Project: Load Test a REST API End to End

Build a complete load test for a REST API: scenarios for browse and checkout, checks, thresholds, custom metrics, and a runnable Node mini-harness that mimics a k6 run against a local server.

Time to put the chapters together. In this project you test a small shop API with two user journeys, assertions, thresholds and a custom metric. You get the real k6 script (read-only, because k6 cannot run in the browser) and a runnable Node mini-harness that executes the same journeys against a local server, so you can see a full run, including a failing threshold.

Honesty note. The k6/* script is real k6 code you can copy to your machine with k6 installed; it is not executed here. The Node harness is a teaching stand-in: it supports virtual users, ramp-up, checks, a custom trend, percentiles and thresholds, but it is not k6 and its numbers say nothing about k6's performance.

The system and the goals

The API (you would point k6 at your staging environment) has three routes:

Route Purpose
GET /products List products
GET /products/:id Product detail
POST /orders Create an order

Goals, written before the first run:

  • p(95) of all requests under 400 ms; checkout under 600 ms.
  • Fewer than 1 % failed requests; more than 99 % of checks pass.
  • Traffic mix: 90 % browsing, 10 % checkout; 20 visitors per second at peak.

The k6 script (read-only)

JavaScript
import http from 'k6/http';
import { check, group, sleep } from 'k6';
import { Trend } from 'k6/metrics';
import { randomIntBetween } from 'https://jslib.k6.io/k6-utils/1.4.0/index.js';

const BASE = __ENV.BASE_URL || 'http://localhost:3000';
const checkoutTime = new Trend('checkout_time', true);
const JSON_HEADERS = { headers: { 'Content-Type': 'application/json' } };

export const options = {
  scenarios: {
    browse: {
      executor: 'ramping-arrival-rate',
      exec: 'browse',
      startRate: 2, timeUnit: '1s',
      preAllocatedVUs: 20, maxVUs: 100,
      stages: [
        { target: 18, duration: '1m' },
        { target: 18, duration: '5m' },
        { target: 0, duration: '30s' },
      ],
    },
    checkout: {
      executor: 'constant-arrival-rate',
      exec: 'checkout',
      rate: 2, timeUnit: '1s', duration: '6m',
      preAllocatedVUs: 10, maxVUs: 50,
    },
  },
  thresholds: {
    http_req_failed: ['rate<0.01'],
    http_req_duration: ['p(95)<400'],
    'http_req_duration{name:CreateOrder}': ['p(95)<600'],
    checks: ['rate>0.99'],
    checkout_time: ['p(95)<1200'],
  },
};

export function browse() {
  group('browse', () => {
    const list = http.get(`${BASE}/products`, { tags: { name: 'ListProducts' } });
    check(list, { 'list is 200': (r) => r.status === 200, 'has items': (r) => r.json().length > 0 });

    const id = randomIntBetween(1, 50);
    const one = http.get(`${BASE}/products/${id}`, { tags: { name: 'ProductDetail' } });
    check(one, { 'detail is 200': (r) => r.status === 200 });
  });
  sleep(randomIntBetween(1, 3));
}

export function checkout() {
  const start = Date.now();
  const res = http.post(`${BASE}/orders`, JSON.stringify({ productId: randomIntBetween(1, 50), qty: 1 }), {
    ...JSON_HEADERS, tags: { name: 'CreateOrder' },
  });
  check(res, { 'order created': (r) => r.status === 201, 'has order id': (r) => !!r.json('id') });
  checkoutTime.add(Date.now() - start);
}

Walk through the design choices:

  • Two open-model scenarios give the 90/10 mix (arrival rates 18 and 2 per second) and each runs its own exported function via exec.
  • Dynamic URLs carry name tags, so results are per route (see Tags and groups).
  • A Trend records a business-level duration (Custom metrics).
  • Thresholds use sub-metrics for the checkout route.
  • The base URL comes from __ENV, so the same file runs against any environment.

Run it with k6 run -e BASE_URL=https://staging.example.test shop.js, then start from a smoke version (vus: 1, duration: '30s') before the full run.

A runnable mini-harness

The Node version below starts a local API (with a simulated limited capacity), runs both journeys with concurrent virtual users, evaluates checks, and prints a summary with threshold verdicts. Press Run and then change the BROKEN constant to see thresholds fail.

Node.js Mini-harness: run journeys, checks and thresholds

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Run it once with BROKEN = false (everything passes), then set it to true and run again: the order route becomes slow and flaky, the checks and thresholds fail and the exit code becomes 99. That is exactly how a real k6 gate behaves in CI (k6 in CI pipelines).

Extend the project

  1. Add authentication in setup() and a bearer header (Authentication and Correlation).
  2. Drive product ids from a SharedArray instead of random numbers (Data and shared files).
  3. Use handleSummary to export a JSON report (End-of-test summary).
  4. Add a stress scenario that increases the arrival rate until http_req_failed crosses 5 %.
  5. Add abortOnFail on the failure-rate threshold with a delayAbortEval of 30 seconds.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why are browse and checkout separate scenarios with arrival rates 18 and 2?

    Each scenario has its own rate and function; 18:2 gives the intended mix, and arrival rates model independent visitors.
  2. 2. What does the name tag 'CreateOrder' enable?

    Tagged requests form a sub-metric, so you can set 'http_req_duration{name:CreateOrder}' separately from the rest.
  3. 3. In the mini-harness, what exit code would indicate a failed threshold?

    k6 exits with 99 when any threshold fails, which CI treats as failure.
  4. 4. Why start with a smoke version of the script?

    A 1-VU, 30-second run catches script mistakes cheaply before you risk a long run.

Summary

  • Write goals and thresholds first, then model the traffic mix with scenarios.
  • Tag dynamic URLs, add a business metric and use sub-metric thresholds.
  • Smoke-test the script, then run the real load; the exit code is the gate.
  • The Node harness showed how checks, percentiles and thresholds produce a verdict.

Next: Project: Spike and Soak Tests with SLOs