Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 36 ยท Scenarios and Executors

Multiple Scenarios and exec

Run several k6 scenarios in one test with exec functions, startTime sequencing, per-scenario env, tags and thresholds, and the execution module to read scenario state.

Production traffic is a mixture: most visitors browse, a few search, a handful check out, and a background job calls an internal API every minute. A realistic test reproduces that mixture. With scenarios you describe each kind of traffic separately, give each its own function (exec), executor, schedule and thresholds, and k6 runs them side by side. This lesson ties together everything from the chapter.

One function per scenario

By default a scenario runs the default function. Use exec to point each scenario at a different exported function.

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

const BASE = __ENV.BASE_URL || 'http://localhost:3000';

export const options = {
  scenarios: {
    browsing: {
      executor: 'constant-vus',
      vus: 40,
      duration: '10m',
      exec: 'browse',
    },
    checkout: {
      executor: 'constant-arrival-rate',
      rate: 5,
      timeUnit: '1s',
      duration: '10m',
      preAllocatedVUs: 10,
      maxVUs: 50,
      exec: 'buy',
    },
  },
  thresholds: {
    'http_req_duration{scenario:browsing}': ['p(95)<400'],
    'http_req_duration{scenario:checkout}': ['p(95)<1500'],
  },
};

export function browse() {
  http.get(`${BASE}/`);
  sleep(Math.random() * 3 + 1);
}

export function buy() {
  const res = http.post(`${BASE}/orders`, JSON.stringify({ sku: 'A1' }), {
    headers: { 'Content-Type': 'application/json' },
  });
  check(res, { 'order created': (r) => r.status === 201 });
}

Both scenarios start at once. Browsing models people who stay (closed model, with think time), checkout models orders arriving at a steady rate (open model, no sleep). Each data point carries a scenario tag, so the thresholds above apply to the right group. The exported functions are ordinary JavaScript functions; the default function is not required when every scenario names an exec.

Scheduling with startTime

startTime delays a scenario. You can place scenarios one after another or overlap them in any pattern:

JavaScript
scenarios: {
  warmup:  { executor: 'constant-vus', vus: 5,  duration: '1m', exec: 'browse' },
  main:    { executor: 'ramping-vus',  startTime: '1m', stages: [
              { duration: '3m', target: 100 }, { duration: '1m', target: 0 } ], exec: 'browse' },
  cron:    { executor: 'constant-arrival-rate', startTime: '2m', rate: 1, timeUnit: '10s',
             duration: '3m', preAllocatedVUs: 1, exec: 'batchJob' },
}
TEXT
minute:     0     1     2     3     4     5
warmup      [=====]
main              [=================]
cron                    [==========]

startTime lets scenarios run in sequence, overlap or leave gaps.

The test duration is the end of the last scenario: here startTime + duration of main is 5 minutes and cron ends at 5 minutes, so the total is 5 minutes. A scenario's gracefulStop adds up to 30 s (the default) after its end, so the run may last slightly longer.

Per-scenario env and tags

The same function can behave differently depending on env:

JavaScript
scenarios: {
  cardPayers:   { executor: 'constant-vus', vus: 10, duration: '5m', exec: 'pay', env: { METHOD: 'card' },    tags: { payment: 'card' } },
  invoicePayers:{ executor: 'constant-vus', vus: 3,  duration: '5m', exec: 'pay', env: { METHOD: 'invoice' }, tags: { payment: 'invoice' } },
}

Inside pay() read __ENV.METHOD. The scenario-level tags apply to every request in that scenario, so you can threshold on http_req_duration{payment:card} without touching the function code.

The execution module

k6/execution exposes information about the running test, valuable when many scenarios and VUs run together:

JavaScript
import exec from 'k6/execution';

export function browse() {
  console.log(exec.scenario.name);              // 'browsing'
  console.log(exec.scenario.iterationInTest);   // unique across the scenario
  console.log(exec.vu.idInTest);                // unique across the whole test
  console.log(exec.instance.currentTestRunDuration); // ms since the start
}

exec.scenario.iterationInTest is the right counter for picking unique test data (see Test Data and Environment Variables), and exec.test.abort('reason') lets a script stop the whole test programmatically.

Rules to remember

  • Every scenario needs an executor; names are free-form identifiers (letters, digits, underscores recommended).
  • Scenarios are independent: no scenario waits for another unless you use startTime.
  • setup() runs once before any scenario starts, and teardown() once after all end.
  • vus, duration and stages at the top level cannot be mixed with scenarios.
  • All functions named by exec must be exported from the script.

A stand-in scenario runner

The program below is not k6. It models the idea: a table of scenarios, each with its own function, schedule and counters, executed concurrently against one local server, with per-scenario results (the scenario tag). A "browse" scenario runs with VUs and think time, a "buy" scenario fires at a fixed rate, and a delayed "cron" scenario starts later. The counts are timing-dependent, so only guaranteed properties are printed.

Node.js Stand-in: scenarios with exec functions and startTime

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.

Browsing, checkout and cron share one server but keep separate counters, and cron starts 200 ms in, because of its startTime.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the exec option of a scenario do?

    exec points a scenario at a specific exported function, letting each scenario run different code.
  2. 2. How do scenarios run by default?

    Scenarios are independent and start at their startTime, which defaults to the beginning of the test.
  3. 3. Which tag lets you write a threshold for one scenario?

    Every data point carries scenario:<name>, so http_req_duration{scenario:checkout} works.
  4. 4. Which value from k6/execution is a good counter for unique test data inside a scenario?

    iterationInTest increases across all VUs of the scenario, so each iteration gets a unique number.

Summary

  • Use scenarios with one exec function per traffic type to model a realistic mixture.
  • startTime sequences or overlaps scenarios; the test lasts until the last one ends.
  • Per-scenario env and tags customise behaviour and metrics; filter thresholds by scenario:name.
  • k6/execution offers scenario, VU and test information, including unique counters and abort.
  • setup() and teardown() are shared by all scenarios.

Next: HTTP Requests, Bodies and Responses in k6