Using k6 Stages, Tags and Environment Variables

k6โ€™s stages, tags and environment variables let you shape realistic load profiles and keep scripts flexible across environments. These features are key for modelling production-like traffic while avoiding hard-coded settings.

Using Stages for Dynamic Load Profiles

Stages allow you to ramp VUs up and down over time, approximating warm-up, peak and cool-down phases. You define an array of stage objects with durations and target VUs, and k6 adjusts concurrency accordingly.

export const options = {
  stages: [
    { duration: '2m', target: 50 },   // ramp-up to 50 VUs
    { duration: '5m', target: 50 },   // stay at 50
    { duration: '2m', target: 200 },  // ramp-up to 200
    { duration: '5m', target: 200 },  // stay at 200 (peak)
    { duration: '3m', target: 0 },    // ramp-down
  ],
};
Note: Stages provide a simple way to express many common load patterns without defining custom scenarios.

Tags and Environment Variables

Tags let you label requests and metrics (for example by endpoint, feature or environment), which makes filtering and aggregating results easier in dashboards. Environment variables (for example __ENV.BASE_URL) keep scripts generic while CI or shell commands supply specific values.

import http from 'k6/http';

const BASE_URL = __ENV.BASE_URL || 'https://api.example.com';

export default function () {
  http.get(`${BASE_URL}/health`, { tags: { endpoint: 'health' } });
}
Tip: Use tags consistently (for example service, endpoint, journey) so dashboards and alerts can group metrics in meaningful ways.
Warning: Hard-coding URLs or credentials in scripts makes it harder to reuse them safely across environments.

With stages, tags and environment variables, k6 scripts become adaptable building blocks for many performance scenarios.

Common Mistakes

Mistake 1 โ€” Using only constant VUs for every test

This misses dynamic behaviour.

โŒ Wrong: Ignoring ramp-up and peak patterns.

โœ… Correct: Use stages or scenarios to reflect real traffic changes.

Mistake 2 โ€” Embedding environment details directly in code

This reduces flexibility.

โŒ Wrong: Hard-coding base URLs or secrets in scripts.

โœ… Correct: Use environment variables and secure configuration mechanisms.

🧠 Test Yourself

Why use environment variables and tags in k6 scripts?