The four lifecycle stages
A k6 test always runs through these stages in order:1
Init context
Prepare the script by loading files, importing modules, and defining lifecycle functions. Runs once per VU.
2
Setup (optional)
Set up the test environment and generate data to share across VUs. Runs once at test start.
3
VU execution
Run the main test function repeatedly for the configured duration or iterations. Each VU runs independently.
4
Teardown (optional)
Clean up the test environment and process results. Runs once at test end.
Lifecycle overview
Basic structure
Here’s the basic structure showing all lifecycle stages:Init context
The init stage is required and runs before the test begins. Code in the init context executes once per VU to initialize the test conditions. All code outside of lifecycle functions is init code and executes first.What belongs in init
Init context restrictions
Init code separates setup from execution, which improves k6 performance and makes test results more reliable.VU execution stage
The VU stage is required and contains the actual test workload. Scripts must define at least one scenario function (typicallydefault) that runs repeatedly.
The default function
The most common pattern uses thedefault function:
VU execution lifecycle
1
Execute function
The VU runs the function from start to finish
2
Reset VU state
k6 clears cookies and may close TCP connections (depending on options)
3
Loop back
The VU immediately starts executing the function again
What VU code can and cannot do
VU code CAN
- Make HTTP requests
- Emit metrics
- Run checks
- Use imported modules
VU code CANNOT
- Load files from filesystem
- Import new modules
- Define new metrics
Setup and teardown
Thesetup and teardown functions are optional lifecycle functions that run once per test.
Setup function
Setup runs once at the beginning of the test, after init but before VU execution:Unlike init code, setup functions can make HTTP requests since they run during test execution.
Teardown function
Teardown runs once at the end of the test, after all VU execution completes:Sharing data between stages
Thesetup() function can return data that gets passed to both default() and teardown():
Data sharing rules
Skipping setup and teardown
You can skip these stages using CLI flags:Scenario functions
Instead of thedefault function, you can define custom scenario functions:
Complete example
Here’s a complete test using all lifecycle stages:Best practices
Minimize init code
Keep init code lightweight. Heavy computation in init slows test startup.
Use setup for dynamic data
Generate test data in setup() and share it across VUs.
Keep VU code focused
VU code should only contain the workload you want to measure.
Handle setup errors
Add error handling to setup() to ensure teardown() runs.