Skip to main content

Testing and QA · Advanced · 28 min

Model realistic traffic with k6 scenarios and arrival rates

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · k6 2.4.0 · Python 3 (practice API)

You will drive a small booking API with three k6 2.4 scenarios at once (browsing, booking and admin) at fixed arrival rates, feed them users from a CSV file, hold each scenario to its own thresholds, and run smoke, load, stress, spike and soak tests from one script.

On this page

A load test that runs ten virtual users in a loop tells you how ten very impatient people behave: each one fires the next request the instant the last one returns. Real traffic does not work like that. People arrive whether or not your server is coping, they read a page before clicking the next one, and different kinds of user (browsers, buyers, staff) hit different parts of the system at different rates.

k6 models this with scenarios. Each scenario has an executor that decides how work is scheduled, and you can run several at once with their own rates, start times and thresholds. The key choice is between two models:

  • Closed model. A fixed number of virtual users (VUs) loop. A new iteration starts only when the previous one finishes, so when the server slows down, the load drops with it. That hides the very slowdown you are trying to find. The constant-vus and ramping-vus executors work this way.
  • Open model. You set an arrival rate, such as 20 iterations a second, and k6 starts them on schedule whatever the server does, adding VUs as needed. The constant-arrival-rate and ramping-arrival-rate executors work this way, and they are what you use when the target is "requests per second".

You will build a small booking API to aim at, prove the difference between the two models with numbers, then write one script that browses, books and runs an admin report together, and reuse it for five kinds of test.

Only load test systems you own, or systems whose owner has agreed in writing to the test, the time and the rate. A stress or spike test against someone else's service looks exactly like an attack, and against your own production it can take real users offline. Run against 127.0.0.1 while you learn, then against a staging copy you control.

Step 1 · Install k6 2.4.0

If you followed the first k6 tutorial, k6 is already installed, and k6 version tells you which release. Otherwise install it now. First install Python 3 for the practice API (Ubuntu Server usually ships it already) and the tools to fetch k6, then check which processor architecture your server uses:

Bash
sudo apt-get update
sudo apt-get install -y ca-certificates curl gpg python3
dpkg --print-architecture

Grafana's apt repository only carries amd64 builds, so the next command depends on that answer.

On amd64 (most Intel and AMD servers), add Grafana's signed repository and install the pinned version:

Bash
curl -fsSL https://dl.k6.io/key.gpg | sudo gpg --batch --yes --dearmor -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 k6=2.4.0
k6 version

Later sudo apt-get upgrade runs keep a repository install up to date.

On arm64 (Graviton, Ampere and Raspberry Pi machines, for example), the repository has no package for you: sudo apt-get install k6 reports Unable to locate package k6. Install the release binary from GitHub instead, checking it against the published checksums:

Bash
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 ~
k6 version

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 are coming from k6 1.x, the scenario and executor options in this tutorial are unchanged in 2.x. Two things you may meet in older scripts and CI jobs are gone: the externally-controlled executor (use ramping-vus or an arrival-rate executor), and the --no-summary flag (use --summary-mode=disabled).

Check it worked

k6 version prints a line starting k6 v2.4.0, followed by build details.

Step 2 · Start a practice booking API

Make a throwaway folder and a random admin token for the API. The token goes in a file created private (only you can read it), so it never appears on a command line or in your shell history:

Bash
mkdir -p ~/k6-scenarios-demo
cd ~/k6-scenarios-demo
(umask 077; python3 -c 'import secrets; print(secrets.token_hex(16))' > .admin-token)

Now write server.py. It lists 20 events, returns one event, accepts bookings, serves an admin report that needs the token, and has a deliberately slow route. Each route sleeps for a few milliseconds to act like a database. Two extra routes help you check your tests: /stats counts requests per route and the distinct users that booked, and /control makes bookings slower on demand.

Bash
cat > server.py <<'PY'
import json
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import urlparse

TOKEN = Path(".admin-token").read_text().strip()
EVENTS = [{"id": i, "name": f"Event {i}", "seats": 100} for i in range(1, 21)]
lock = threading.Lock()
state = {"routes": {}, "users": set(), "booking_delay_ms": 0}


def count(route):
    with lock:
        state["routes"][route] = state["routes"].get(route, 0) + 1


class Handler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"

    def reply(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 read_json(self):
        length = int(self.headers.get("Content-Length", 0))
        try:
            return json.loads(self.rfile.read(length) or b"{}")
        except ValueError:
            return None

    def do_GET(self):
        path = urlparse(self.path).path
        if path == "/api/events":
            count("list")
            time.sleep(0.01)
            return self.reply(200, EVENTS)
        if path.startswith("/api/events/"):
            count("detail")
            time.sleep(0.015)
            wanted = path.rsplit("/", 1)[1]
            for event in EVENTS:
                if str(event["id"]) == wanted:
                    return self.reply(200, event)
            return self.reply(404, {"error": "no such event"})
        if path == "/api/slow":
            count("slow")
            time.sleep(0.6)
            return self.reply(200, {"slow": True})
        if path == "/admin/report":
            if self.headers.get("Authorization") != f"Bearer {TOKEN}":
                return self.reply(401, {"error": "unauthorised"})
            count("report")
            time.sleep(0.12)
            with lock:
                booked = state["routes"].get("book", 0)
            return self.reply(200, {"bookings": booked})
        if path == "/stats":
            with lock:
                return self.reply(200, {
                    "routes": dict(sorted(state["routes"].items())),
                    "distinct_users": len(state["users"]),
                    "booking_delay_ms": state["booking_delay_ms"],
                })
        self.reply(404, {"error": "not found"})

    def do_POST(self):
        path = urlparse(self.path).path
        data = self.read_json()
        if data is None:
            return self.reply(400, {"error": "send JSON"})
        if path == "/api/bookings":
            if not data.get("email") or not data.get("eventId"):
                return self.reply(422, {"error": "email and eventId are required"})
            with lock:
                delay = state["booking_delay_ms"]
            time.sleep(0.04 + delay / 1000)
            with lock:
                state["routes"]["book"] = state["routes"].get("book", 0) + 1
                state["users"].add(data["email"])
            return self.reply(201, {"email": data["email"], "name": data.get("name", ""), "eventId": data["eventId"]})
        if path == "/stats/reset":
            with lock:
                state["routes"].clear()
                state["users"].clear()
            return self.reply(200, {"reset": True})
        if path == "/control":
            with lock:
                state["booking_delay_ms"] = int(data.get("booking_delay_ms", 0))
            return self.reply(200, {"booking_delay_ms": state["booking_delay_ms"]})
        self.reply(404, {"error": "not found"})

    def log_message(self, format, *args):
        pass


ThreadingHTTPServer(("127.0.0.1", 8090), Handler).serve_forever()
PY

In your second terminal, start it from the same folder and leave it running:

Bash
cd ~/k6-scenarios-demo
python3 server.py

It listens only on 127.0.0.1, keeps everything in memory and has no protection on /stats or /control. It is a target for practice, nothing more. Run every command from here on in your first terminal, inside ~/k6-scenarios-demo.

Check it worked

Bash
curl -s http://127.0.0.1:8090/api/events/3; echo
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8090/admin/report

The first line is {"id": 3, "name": "Event 3", "seats": 100}. The second is 401, because you sent no token.

Step 3 · Compare a closed model with an open model

Write two scripts that aim at the same path. closed.js keeps 5 VUs looping for 10 seconds. open.js asks for 20 iterations a second for 10 seconds, starts with 5 VUs, and lets k6 add up to 30 if iterations pile up. The path comes from an environment variable so you can point both at a fast route and a slow one:

Bash
cat > closed.js <<'JS'
import http from 'k6/http';

const BASE_URL = __ENV.BASE_URL || 'http://127.0.0.1:8090';
const TARGET_PATH = __ENV.TARGET_PATH || '/api/events';

export const options = {
  scenarios: {
    closed: { executor: 'constant-vus', vus: 5, duration: '10s' },
  },
};

export default function () {
  http.get(`${BASE_URL}${TARGET_PATH}`);
}
JS

cat > open.js <<'JS'
import http from 'k6/http';

const BASE_URL = __ENV.BASE_URL || 'http://127.0.0.1:8090';
const TARGET_PATH = __ENV.TARGET_PATH || '/api/events';

export const options = {
  scenarios: {
    open: {
      executor: 'constant-arrival-rate',
      rate: 20,
      timeUnit: '1s',
      duration: '10s',
      preAllocatedVUs: 5,
      maxVUs: 30,
    },
  },
};

export default function () {
  http.get(`${BASE_URL}${TARGET_PATH}`);
}
JS

rate and timeUnit together are the arrival rate: 20 per 1s. An iteration is one call of the default function, so here one iteration is one request. Run the closed model against the fast list route, then against the slow route, resetting the server's counters before each run and reading them after:

Bash
curl -s -X POST http://127.0.0.1:8090/stats/reset; echo
k6 run --quiet closed.js
curl -s http://127.0.0.1:8090/stats; echo
Bash
curl -s -X POST http://127.0.0.1:8090/stats/reset; echo
k6 run --quiet -e TARGET_PATH=/api/slow closed.js
curl -s http://127.0.0.1:8090/stats; echo

Now the open model against the same slow route:

Bash
curl -s -X POST http://127.0.0.1:8090/stats/reset; echo
k6 run --quiet -e TARGET_PATH=/api/slow open.js
curl -s http://127.0.0.1:8090/stats; echo

With the closed model, the same 5 VUs made thousands of fast requests but only about 80 slow ones: each VU waits 0.6 seconds per answer, so the slower the server, the gentler the test. That is a form of coordinated omission. The test quietly backs off at the moment it should be measuring. The open model kept its promise of about 200 requests, because k6 brought in more VUs (about 12 are busy at once when each request takes 0.6 seconds at 20 a second).

If an arrival-rate scenario needs more VUs than maxVUs allows, k6 skips the iterations it cannot start, counts them in the dropped_iterations metric, and warns you in the output. A dropped iteration means your load generator, not your server, set the limit, so size maxVUs with room to spare: roughly the rate times the longest iteration time you expect, then double it.

Check it worked

The three /stats readings show list in the thousands (closed, fast route), slow at about 80 (closed, slow route), and slow at about 200 (open, slow route). The exact counts vary by machine, but the open run stays close to 200 whatever the route.

Step 4 · Write the user journeys and load test data from a CSV

Real users bring real data: different accounts, different events, names in many scripts. Put a few test users in users.csv. The addresses use example.test, a domain reserved for testing, and the names include accented and tone-marked letters, so you also check the API handles UTF-8 end to end. In multilingual markets such as Nigeria, Senegal or South Africa, names like these are normal, and an API that mangles them fails real people.

Bash
cat > users.csv <<'CSV'
email,name,eventId
amara@example.test,Amara Okafor,3
wanjiru@example.test,Wanjiru Kamau,7
kofi@example.test,Kofi Mensah,12
zanele@example.test,Zanele Dlamini,5
seun@example.test,Olúwaseun Adébáyọ̀,9
fatou@example.test,Fatou Ndiaye,15
lina@example.test,Lina Haddad,1
mateo@example.test,Mateo García,20
CSV

Now journeys.js, a module holding the three things your users do, plus the goals each must meet. Scenarios in the next step call these functions:

Bash
cat > journeys.js <<'JS'
import http from 'k6/http';
import { check, sleep } from 'k6';
import { SharedArray } from 'k6/data';
import exec from 'k6/execution';

const BASE_URL = __ENV.BASE_URL || 'http://127.0.0.1:8090';
const ADMIN_TOKEN = __ENV.ADMIN_TOKEN;
if (!ADMIN_TOKEN) {
  throw new Error('Set ADMIN_TOKEN in the environment before running k6.');
}

// Parsed once, then shared read-only between every VU.
const users = new SharedArray('users', function () {
  const [header, ...rows] = open('./users.csv').trim().split(/\r?\n/);
  const keys = header.split(',');
  return rows.map((line) => {
    const values = line.split(',');
    return Object.fromEntries(keys.map((key, i) => [key, values[i]]));
  });
});

export function browse() {
  const list = http.get(`${BASE_URL}/api/events`, { tags: { name: 'events-list' } });
  check(list, {
    'list is 200': (r) => r.status === 200,
    'list has events': (r) => r.status === 200 && r.json().length > 0,
  });

  sleep(0.5 + Math.random()); // think time: 0.5 to 1.5 seconds reading the list

  const id = Math.floor(Math.random() * 20) + 1;
  const detail = http.get(`${BASE_URL}/api/events/${id}`, { tags: { name: 'event-detail' } });
  check(detail, { 'detail is 200': (r) => r.status === 200 });
}

export function book() {
  const user = users[exec.scenario.iterationInTest % users.length];
  const body = JSON.stringify({ email: user.email, name: user.name, eventId: Number(user.eventId) });
  const res = http.post(`${BASE_URL}/api/bookings`, body, {
    headers: { 'Content-Type': 'application/json' },
    tags: { name: 'create-booking' },
  });
  check(res, {
    'booking is 201': (r) => r.status === 201,
    'name survives the round trip': (r) => r.status === 201 && r.json().name === user.name,
  });
}

export function admin() {
  const res = http.get(`${BASE_URL}/admin/report`, {
    headers: { Authorization: `Bearer ${ADMIN_TOKEN}` },
    tags: { name: 'admin-report' },
  });
  check(res, { 'report is 200': (r) => r.status === 200 });
  sleep(2); // staff read the report before refreshing it
}

export const thresholds = {
  http_req_failed: ['rate<0.01'],
  checks: ['rate>0.99'],
  dropped_iterations: ['count<5'],
  'http_req_duration{scenario:browse}': ['p(95)<400'],
  'http_req_duration{scenario:booking}': ['p(95)<300'],
  'http_req_duration{scenario:admin}': ['p(95)<1000'],
  'http_req_duration{name:event-detail}': ['p(99)<500'],
};
JS

A few details matter here:

  • open() and new SharedArray() run once, in the init stage before any VU starts. Without SharedArray, every VU would hold its own copy of the file, which adds up quickly at hundreds of VUs and a large CSV.
  • exec.scenario.iterationInTest counts iterations across the whole scenario, so bookings walk through the users in order instead of all VUs picking the same row. Use Math.random() instead when order does not matter.
  • The name tag groups /api/events/1 to /api/events/20 under one label, so the summary and thresholds treat them as one endpoint instead of 20.
  • The sleep() calls are think time: a person reading. In the open model, think time does not lower the arrival rate. It makes each iteration last longer, so k6 needs more VUs to keep the rate.
  • The token comes from the ADMIN_TOKEN environment variable. k6 copies your shell's environment variables into __ENV, so the token never sits in the script or on the k6 command line.
  • The CSV parser is a simple split on commas. If your data has quoted fields with commas inside them, use a proper CSV parser.

Export the token into this terminal's environment, then run each journey once from a short script that calls all three:

Bash
export ADMIN_TOKEN="$(cat .admin-token)"
cat > try.js <<'JS'
import { browse, book, admin } from './journeys.js';

export default function () {
  browse();
  book();
  admin();
}
JS
curl -s -X POST http://127.0.0.1:8090/stats/reset; echo
k6 run --quiet --iterations 1 try.js
curl -s http://127.0.0.1:8090/stats; echo

Check it worked

In the k6 summary, the checks line shows 100% passed (6 checks). The /stats line shows one request each for book, detail, list and report, and "distinct_users": 1. If k6 stops with "Set ADMIN_TOKEN in the environment", you skipped the export line in this terminal.

Step 5 · Run browsing, booking and admin traffic together

Now describe the traffic. Most visitors browse, fewer book, and one member of staff watches the report. Each gets its own scenario and executor in traffic.js:

Bash
cat > traffic.js <<'JS'
import { browse, book, admin, thresholds } from './journeys.js';

// Scenarios call exported functions by name, so re-export the journeys.
export { browse, book, admin };

export const options = {
  scenarios: {
    browse: {
      executor: 'ramping-arrival-rate',
      exec: 'browse',
      startRate: 2,
      timeUnit: '1s',
      preAllocatedVUs: 20,
      maxVUs: 60,
      stages: [
        { target: 10, duration: '10s' }, // morning ramp: 2 to 10 visits a second
        { target: 10, duration: '10s' }, // hold
        { target: 0, duration: '5s' },   // tail off
      ],
    },
    booking: {
      executor: 'constant-arrival-rate',
      exec: 'book',
      rate: 3,
      timeUnit: '1s',
      duration: '20s',
      startTime: '5s', // bookings begin once people have browsed
      preAllocatedVUs: 5,
      maxVUs: 20,
    },
    admin: {
      executor: 'constant-vus',
      exec: 'admin',
      vus: 1,
      duration: '25s',
    },
  },
  thresholds,
};
JS
curl -s -X POST http://127.0.0.1:8090/stats/reset; echo
k6 run traffic.js
curl -s http://127.0.0.1:8090/stats; echo

Three executors appear together, each chosen for what it models:

  • browse uses ramping-arrival-rate: visits per second that change over time. startRate is where it begins, and each stage moves the rate linearly to its target over its duration.
  • booking uses constant-arrival-rate: a steady 3 bookings a second, starting 5 seconds in. startTime lets you stagger scenarios, or run them one after another.
  • admin uses constant-vus on purpose. One person refreshing a report is a closed loop: they wait for the page, read it, refresh. Not every scenario should be open.

While it runs, the progress display shows one line per scenario. The summary at the end reports every metric across all scenarios, and the thresholds section lists each threshold from journeys.js with its result. The thresholds object came along with the journeys, and the next step looks at it closely.

Check it worked

k6 exits normally after about 25 seconds with every threshold passing. /stats shows book at about 60 (3 a second for 20 seconds), list and detail at about 185 each, report at about 12, and "distinct_users": 8, one for each row of users.csv.

Step 6 · Hold each scenario to its own threshold and watch one fail

Look at the thresholds at the end of journeys.js. The first three apply to the whole test: under 1% failed requests, over 99% passing checks, and fewer than 5 dropped iterations (so a run where k6 could not generate the load you asked for fails instead of looking healthy). The rest are written as metric{tag:value}, which limits a threshold to the requests carrying that tag:

  • k6 adds a scenario tag to every request, so http_req_duration{scenario:booking} is the booking latency alone. Bookings can have a tighter goal than browsing without browsing traffic hiding a slow checkout.
  • http_req_duration{name:event-detail} uses the name tag you set in the journey, and holds one endpoint to a p99 goal.

A total p95 would average away a slow checkout under a crowd of fast list pages. To see a per-scenario threshold catch exactly that, make bookings half a second slower, as if a database lock appeared, and run again. The script below records k6's exit code instead of stopping:

Bash
curl -s -X POST http://127.0.0.1:8090/control -H 'Content-Type: application/json' -d '{"booking_delay_ms": 500}'; echo
curl -s -X POST http://127.0.0.1:8090/stats/reset; echo
status=0
k6 run traffic.js || status=$?
echo "k6 exit code: $status"

Then put the API back to normal speed:

Bash
curl -s -X POST http://127.0.0.1:8090/control -H 'Content-Type: application/json' -d '{"booking_delay_ms": 0}'; echo

The run still finishes, because thresholds are judged at the end. Add abortOnFail: true to a threshold, in the long form { threshold: 'p(95)<300', abortOnFail: true }, when you want k6 to stop a long test as soon as it is clearly lost.

Check it worked

The summary marks http_req_duration{scenario:booking} as failed, with a p95 above 500 ms, while the browse, admin and event-detail thresholds still pass. The last line reads k6 exit code: 99, the code k6 uses for failed thresholds, which is what makes a CI job fail. The /control reply shows {"booking_delay_ms": 0} again.

Step 7 · Turn one script into smoke, load, stress, spike and soak tests

The five common test types differ only in shape: how high the rate goes, how fast it gets there and how long it stays. Keep one script with the journeys and thresholds fixed, and choose the shape with an environment variable. Write suite.js:

Bash
cat > suite.js <<'JS'
import { browse, book, admin, thresholds } from './journeys.js';

export { browse, book, admin };

// Browse visits per second over [seconds, target] stages. Bookings run at a quarter of that.
const PROFILES = {
  smoke: { start: 1, stages: [[60, 1]] },
  load: { start: 0, stages: [[300, 10], [600, 10], [120, 0]] },
  stress: { start: 0, stages: [[300, 10], [300, 20], [300, 30], [300, 40], [120, 0]] },
  spike: { start: 2, stages: [[60, 2], [30, 50], [120, 50], [30, 2], [60, 0]] },
  soak: { start: 0, stages: [[300, 8], [7200, 8], [300, 0]] },
};

const profileName = __ENV.PROFILE || 'smoke';
const profile = PROFILES[profileName];
if (!profile) {
  throw new Error(`Unknown PROFILE "${profileName}". Use one of: ${Object.keys(PROFILES).join(', ')}`);
}

// TIME_SCALE=0.01 runs the same shape a hundred times faster, for rehearsals.
const scale = Number(__ENV.TIME_SCALE || 1);
const secs = (s) => Math.max(1, Math.round(s * scale));
const stagesAt = (share) =>
  profile.stages.map(([s, target]) => ({ duration: `${secs(s)}s`, target: Math.ceil(target * share) }));
const peak = Math.max(profile.start, ...profile.stages.map(([, target]) => target));
const totalSeconds = profile.stages.reduce((sum, [s]) => sum + secs(s), 0);

export const options = {
  scenarios: {
    browse: {
      executor: 'ramping-arrival-rate',
      exec: 'browse',
      startRate: profile.start,
      timeUnit: '1s',
      preAllocatedVUs: peak * 2 + 2,
      maxVUs: peak * 4 + 10,
      stages: stagesAt(1),
    },
    booking: {
      executor: 'ramping-arrival-rate',
      exec: 'book',
      startRate: Math.ceil(profile.start * 0.25),
      timeUnit: '1s',
      preAllocatedVUs: Math.ceil(peak * 0.5) + 2,
      maxVUs: peak + 10,
      stages: stagesAt(0.25),
    },
    admin: { executor: 'constant-vus', exec: 'admin', vus: 1, duration: `${totalSeconds}s` },
  },
  thresholds,
  tags: { profile: profileName },
};
JS

What each profile is for:

  • smoke: one visit a second for a minute. Run it after every deploy or script change to prove the journeys and thresholds work before you spend time on anything bigger.
  • load: the traffic you expect on a normal busy day, held for 10 minutes. This is the run your thresholds are really written for.
  • stress: steps beyond normal, 10 then 20, 30 and 40 a second, to find where latency or errors start to climb.
  • spike: a jump from 2 to 50 a second in 30 seconds, like a promotion going out by SMS or a link shared in a busy group chat, then back down. Watch whether the system recovers once the spike passes.
  • soak: a moderate rate for two hours, to find slow leaks: memory growth, full disks, connection pools that never give connections back.

The rates here suit the practice API. For your own system, take them from real figures (your analytics or access logs at the busiest hour), not guesses. The global tags option labels every metric with the profile name, which helps when you send results from several runs to the same dashboard.

Run the smoke test at full length, about a minute:

Bash
k6 run -e PROFILE=smoke suite.js

Before the long runs, rehearse every profile in a few seconds with TIME_SCALE. Each runs the same stages and rates, compressed, so you catch a typo in a profile now and not an hour into a soak test:

Bash
for run in load:0.005 stress:0.005 spike:0.01 soak:0.001; do
  echo "== ${run%%:*} =="
  k6 run --quiet -e PROFILE="${run%%:*}" -e TIME_SCALE="${run##*:}" suite.js
done

When the rehearsals pass, run the real thing against the staging system you own, for example k6 run -e PROFILE=load -e BASE_URL=https://staging.example.test suite.js (replace the address with yours). A full soak run takes 2 hours and 10 minutes, so start it from a server, not a laptop that might sleep.

If you run k6 from a laptop on prepaid mobile data against a remote server, every response counts against your bundle. A hundred requests a second with 20 KB responses is about 7 GB an hour. Run long tests from a machine in the same network or cloud region as the target instead.

Check it worked

The smoke run takes a little over a minute and passes every threshold. Each rehearsal prints a summary under its == name == heading and passes too. A mistyped profile name, such as PROFILE=sopke, stops k6 at once with Unknown PROFILE "sopke" and the list of valid names.

Step 8 · Clean up

Stop the practice API with Ctrl+C in the second terminal. Then remove the demo folder, which also deletes the admin token, and clear the token from this terminal:

Bash
cd ~
rm -rf ~/k6-scenarios-demo
unset ADMIN_TOKEN

k6 stays installed for the next tutorial. To remove it later on amd64, run sudo apt-get remove k6 and delete /etc/apt/sources.list.d/k6.list and /usr/share/keyrings/k6-archive-keyring.gpg. On arm64, delete the binary with sudo rm /usr/local/bin/k6.

Check it worked

ls ~/k6-scenarios-demo reports that there is no such file or directory, and curl -s http://127.0.0.1:8090/stats returns nothing because the API is stopped.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.