Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 36 ยท Concepts and Scripts

The k6 Script Lifecycle

Learn the four stages of a k6 script, init code, setup, the default function and teardown, what runs how often, how data passes between them, and the common mistakes.

A k6 script is not run top to bottom once. It is split into four lifecycle stages, and each stage runs a different number of times and in a different place. Knowing which code belongs in which stage is the single most useful structural idea in k6: put something in the wrong stage and you either repeat expensive work a million times or share state that should be private.

Stage Where in the script How often it runs Typical use
init top level, outside any function once per VU (plus once to read options) imports, options, loading test data
setup export function setup() once, before the test create test users, log in, seed data
VU code export default function repeatedly, per VU the actual test
teardown export function teardown(data) once, after the test delete test data, send a notification
flowchart LR
  A["init<br/>(each VU)"] --> B["setup()<br/>once"]
  B --> C["default()<br/>many iterations<br/>per VU"]
  C --> D["teardown(data)<br/>once"]

Setup runs before any VU starts iterating, teardown after all of them are done.

Init code

Everything at the top level runs during the init stage. k6 runs it once to learn your options, and then once more for every VU, each in its own runtime. This is where import statements, the options object and read-only data loading live.

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

const BASE = __ENV.BASE_URL || 'http://localhost:3000';
const users = JSON.parse(open('./users.json')); // read once per VU

export const options = { vus: 10, duration: '1m' };

Two rules apply in init:

  • You may call open() to read a local file (only here), but not make HTTP requests. Network calls in init code are not allowed.
  • Anything heavy is multiplied by the number of VUs. Parsing a 50 MB JSON file in init with 500 VUs holds 500 copies in memory. The SharedArray helper in Test Data and Environment Variables fixes this.

The default function

The default function is your test. It is the body of one iteration, and each VU calls it repeatedly. Everything you want measured goes here. It receives whatever setup() returned as its argument.

JavaScript
export default function (data) {
  http.get(`${BASE}/products/${data.productId}`);
  sleep(1);
}

Local variables inside the function are fresh on each iteration. Variables declared in init persist across iterations for that VU, which is occasionally useful (a cached token, a counter) and occasionally a bug.

setup and teardown

setup() runs once for the whole test, before the VUs start their iterations. Unlike init code, setup can make HTTP requests. It is the place to create a test account or fetch a token that all VUs will share. Whatever setup() returns is serialized to JSON and passed to every default call and to teardown.

JavaScript
export function setup() {
  const res = http.post(`${BASE}/api/test-session`, null);
  return { token: res.json('token'), startedAt: Date.now() };
}

export default function (data) {
  http.get(`${BASE}/api/me`, {
    headers: { Authorization: `Bearer ${data.token}` },
  });
}

export function teardown(data) {
  http.del(`${BASE}/api/test-session`, null, {
    headers: { Authorization: `Bearer ${data.token}` },
  });
}

Things to remember:

  • The returned data must be JSON-serializable: no functions, no class instances. It is copied for every VU, so keep it small.
  • Setup and teardown are not counted in your VU iteration metrics, but HTTP requests they make are counted in the HTTP metrics unless you tag them out.
  • If setup() throws, the test aborts before any load is generated. That is a feature: a broken prerequisite should not produce meaningless numbers.
  • teardown runs even if thresholds fail, but not if you press Ctrl+C twice (a hard stop).
  • Setup and teardown run on one VU only. They have a default time limit of 60 seconds each (setupTimeout, teardownTimeout in the options).

Experiment with the order

The program below is not k6; it is a tiny runner written in Node.js that imitates the lifecycle. It calls init once per VU, setup once, the default function several times per VU, and teardown once, so you can see the counts and the order, and how setup data reaches the iterations.

Node.js Stand-in: a mini lifecycle runner

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.

Notice that each VU's counter reaches 3 independently (state is per VU), while setup and teardown appear exactly once.

Common mistakes

  1. HTTP requests in init. They fail, and also would be repeated per VU. Move them to setup.
  2. Sharing state through globals. Two VUs never see the same variable. Share through setup data (read-only) or through an external system.
  3. Mutating setup data. The object is a per-VU copy; changes do not reach other VUs.
  4. Heavy open() plus JSON.parse in init. Use SharedArray for large lists.
  5. Forgetting that __ITER is per VU. It restarts at 0 for each VU, so two VUs both have an iteration 0.

For tests with multiple scenarios, each scenario can name its own function with exec instead of using default (see Multiple Scenarios and exec); setup and teardown stay shared.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How often does init code (top level of the script) run?

    Each VU runs the init code once, in its own runtime. k6 also runs it once to read the options.
  2. 2. Where may you make an HTTP request to create a test user before the load starts?

    setup() runs once before the test and can make HTTP requests. Init code cannot.
  3. 3. What must setup() return value be like?

    The value is serialized to JSON and passed to every default call and to teardown.
  4. 4. When does teardown() run?

    teardown runs once at the end of the test, even if thresholds fail.

Summary

  • A script has four stages: init (per VU), setup (once), default (many times), teardown (once).
  • Put imports, options and file reads in init; the test itself in default.
  • setup() can make requests and returns JSON data that every iteration and teardown receives.
  • Avoid network calls and heavy work in init; avoid assuming shared globals between VUs.

Next: Options and Stages