Most Asked k6 Interview Questions: Scripting (2026)

Most asked k6 scripting interview questions: lifecycle, setup data, SharedArray, correlation, tags, custom metrics and handleSummary, with code.

Sep 27, 2025 - 16:24
Nov 16, 2026 - 06:17
 0  50
Most Asked k6 Interview Questions: Scripting (2026)

The k6 interview questions asked most often are about scripting: the four lifecycle stages, what you can and cannot do in init code, passing data from setup(), loading test data with SharedArray, correlating tokens between requests, tagging and grouping requests, custom metrics, and handleSummary for reports. This post answers each with a short code example you can run.

Concept questions about executors, checks and thresholds are in the k6 FAQ quick reference. This page is about writing the script. For the full k6 question bank, see k6 engineer interview questions and 65+ k6 interview questions. Examples follow the current k6 documentation and the v2 release line (v2.4.0 was the latest GitHub release in November 2026).

Key takeaways

  • A k6 script runs in four stages: init, setup, VU code and teardown. Init runs once per VU; setup and teardown run once per test.
  • Init code cannot make HTTP requests. Use it for imports, options and file loading with open().
  • Data returned by setup() must be JSON-compatible, and each VU gets its own copy.
  • SharedArray must be created in init code, is read-only and saves memory on large datasets.
  • Exporting handleSummary() replaces the default end-of-test summary with whatever outputs you return.

Lifecycle at a glance

StageRunsCan make HTTP requests?Typical use
initOnce per VUNoImports, options, open() files, SharedArray
setup()Once, before VUs startYesGet a token, create test data
VU code (default or scenario function)Once per iterationYesThe user journey
teardown()Once, after VU codeYesDelete test data
handleSummary()Once, at the very endNot the purposeCustom reports to stdout or files

Lifecycle questions

1. Explain the k6 test lifecycle.

k6 runs init code first, once per VU, to load modules, options and files. Then setup() runs once before load starts. Next, every VU runs the default function (or its scenario function) repeatedly; each run is an iteration. Finally teardown() runs once. If setup() throws an error, teardown() does not run, which matters if setup half-created test data.

2. Why can't init code make HTTP requests?

Init code runs for every VU before the test starts, and k6 uses it to prepare the VUs. Requests there would multiply by the VU count and would not be measured as part of the test. Put one-off calls such as fetching a token in setup().

3. How do you pass data from setup to VUs?

Return it from setup(). k6 passes it as the first argument to the default function and to teardown(). The data must be JSON-compatible, so no functions. Each VU gets its own copy, so changes a VU makes do not reach other VUs or teardown.

import http from 'k6/http';

export function setup() {
  const res = http.post('https://api.example.com/login',
    JSON.stringify({ user: __ENV.USER, pass: __ENV.PASS }),
    { headers: { 'Content-Type': 'application/json' } });
  return { token: res.json('token') };
}

export default function (data) {
  http.get('https://api.example.com/orders', {
    headers: { Authorization: `Bearer ${data.token}` },
  });
}

export function teardown(data) {
  // clean up test records here
}

4. setup() is slow and the test fails before it starts. Why?

Setup has a default timeout of 60 seconds, controlled by the setupTimeout option. If setup takes longer, the test fails before any VU starts. Raise the timeout or move heavy data preparation out of the test.

5. How do you skip setup or teardown for a quick run?

Use the --no-setup and --no-teardown flags. This is useful when you are debugging the VU code against data that already exists.

Test data questions

6. How do you load a CSV or JSON file of users?

Use open() in init code to read the file, parse it, and wrap it in a SharedArray. For CSV, a parser such as papaparse from the k6 jslib can be used inside the SharedArray function.

import { SharedArray } from 'k6/data';

const users = new SharedArray('users', function () {
  return JSON.parse(open('./users.json'));
});

export default function () {
  const user = users[Math.floor(Math.random() * users.length)];
  // log in as user.username
}

7. Why use SharedArray instead of a normal array?

A normal array is copied into every VU's memory. A SharedArray runs its loading function once and shares the data across VUs. The k6 docs show the savings grow with dataset size and are small below about a thousand lines. It must be created in init code; creating it elsewhere throws an error.

8. Can VUs write to a SharedArray to share state?

No. A SharedArray is read-only after it is built. VUs in k6 do not share mutable state; each VU runs in its own JavaScript runtime.

9. How do you give each VU a different user?

Use the VU number. The k6/execution module exposes exec.vu.idInTest, which you can use as an index into your SharedArray. For unique data per iteration across the whole test, use exec.scenario.iterationInTest.

import exec from 'k6/execution';

export default function () {
  const user = users[(exec.vu.idInTest - 1) % users.length];
}

10. How do you pass settings such as the base URL?

Use environment variables. Pass them with -e or as system environment variables, and read them through __ENV. Keep secrets out of the script file.

k6 run -e BASE_URL=https://staging.example.com script.js

Request and correlation questions

11. What is correlation and how do you do it in k6?

Correlation means taking a dynamic value from one response, such as a session token or order ID, and using it in later requests. In k6 you parse the response with res.json() for JSON APIs, or use the HTML parsing helpers for forms, then pass the value into the next request.

const create = http.post(`${__ENV.BASE_URL}/orders`, JSON.stringify({ sku: 'A1' }),
  { headers: { 'Content-Type': 'application/json' } });
const orderId = create.json('id');
http.get(`${__ENV.BASE_URL}/orders/${orderId}`);

12. How do you send several requests at once?

Use http.batch() with an array of requests. k6 sends them in parallel from the same VU, like a browser loading several assets for one page.

13. Why do URLs with IDs make metrics messy, and how do you fix it?

Each unique URL becomes its own tag value, so /orders/1, /orders/2 and so on split your metrics into thousands of series. Set the name tag, for example { tags: { name: 'GetOrder' } }, or use the http.url template literal helper so they group together.

14. How do you validate a response?

Use check() with named conditions on the status code, body content or JSON fields. Checks do not stop the iteration or fail the test on their own; add a threshold on the checks rate if failures should fail the run.

import { check } from 'k6';

check(res, {
  'status 200': (r) => r.status === 200,
  'has order id': (r) => r.json('id') !== undefined,
});

15. How do you add think time correctly?

Call sleep() between steps of the journey, ideally with a small random range, so VUs do not hit the server in lockstep. Leave sleep out of arrival-rate tests only if you have designed the rate to account for it.

Structure and metrics questions

16. When do you use group() and when do you use tags?

group() wraps steps of a journey, such as "login" or "checkout", and reports a duration for the group. Tags label individual requests or checks so you can filter results and set thresholds on a subset. Use groups for readable structure and tags for analysis.

17. How do you create a custom metric?

Import a metric type from k6/metrics (Counter, Gauge, Rate or Trend), create it in init code and add values in VU code. A Trend suits timings because you can set percentile thresholds on it.

import { Trend } from 'k6/metrics';
const checkoutTime = new Trend('checkout_time', true);

export const options = {
  thresholds: { checkout_time: ['p(95)<800'] },
};

export default function () {
  const start = Date.now();
  // checkout requests here
  checkoutTime.add(Date.now() - start);
}

18. How do you set a threshold for one endpoint only?

Use a tag filter in the threshold name, for example 'http_req_duration{name:GetOrder}': ['p(95)<300']. This lets you hold a strict target on the critical API while allowing slower reports elsewhere.

19. How do you run different code for different scenarios?

Export named functions and point each scenario at one with the exec option. Each scenario can then have its own executor and tags, while sharing init code and data.

Reporting questions

20. What does handleSummary() do?

If you export handleSummary(data), k6 calls it at the end of the test with aggregated metrics. It returns an object whose keys are stdout, stderr or file paths, and whose values are strings. Exporting it turns off the default summary, so import textSummary from the k6 jslib if you still want the normal text on screen.

import { textSummary } from 'https://jslib.k6.io/k6-summary/0.0.2/index.js';

export function handleSummary(data) {
  return {
    stdout: textSummary(data, { indent: ' ', enableColors: true }),
    'summary.json': JSON.stringify(data),
  };
}

21. How do you keep reports from CI runs?

Write a JSON summary with handleSummary() and publish it as a CI artifact, or stream metrics to a time-series database during the run. For trend lines across builds, the database route is easier to chart. The real-time k6 results questions cover reading those numbers.

22. How do you debug a k6 script that returns unexpected responses?

Run it with one VU and one iteration, add console.log() calls for status codes and key fields, and use the --http-debug flag to print request and response headers (--http-debug=full adds bodies). Keep debug runs away from production data, since the output can include tokens. Remove the logging before a real load run because printing on every iteration slows VUs down.

23. How do you reuse code across several k6 scripts?

Put shared functions in local JavaScript modules and import them with relative paths, for example a lib/auth.js that handles login. k6 can also import remote modules over HTTPS, such as the utilities published on jslib.k6.io. Pin remote modules to a version in the URL, as with k6-summary/0.0.2, so a change upstream does not alter your tests without warning.

Scenario questions

24. The test shows thousands of 401 errors after a few minutes. What happened?

The token fetched in setup() probably expired, and every VU still uses it. Either refresh the token inside VU code when it is near expiry, or log in per VU at the start of its first iteration.

25. Memory on the load generator keeps growing. What do you check?

Large test data in normal arrays (move it to SharedArray), many unique URL tags (use the name tag), and storing response bodies you do not need. The discardResponseBodies option helps when you only need status codes.

26. Your script works with 1 VU but fails with 50. Why?

Usually test data collisions: every VU uses the same user or the same record, and the application locks or rejects duplicates. Give each VU unique data using exec.vu.idInTest or iteration-based indexing.

27. A teammate's script reports great response times, but users complain. What might be wrong?

Check what the script actually requests. Scripts often hit one cached endpoint over and over, skip the slow pages, or never log in, so they measure the easy path. Compare the script's request mix with real traffic from access logs or analytics, add the missing steps, and use realistic test data so caches do not serve every response. Also confirm that checks pass: fast responses that return error pages are not good news, which is why a threshold on the checks rate is worth adding.

28. How do you make a check failure fail the whole test?

Checks only record results. Add a threshold on the built-in checks metric, such as a rate above 0.99, so k6 exits with a non-zero code when too many checks fail. You can also tag checks and set thresholds on a tagged subset when one journey matters more than others. The k6 FAQ explains how thresholds drive the exit code in CI.

29. What should go in teardown()?

Clean-up of anything setup() created, such as test accounts or orders, so repeated runs start from the same state. Remember that teardown receives the data returned by setup, not changes made by VUs, and that it does not run if setup threw an error. Write setup so it fails early and leaves little behind.

Practice plan

Write one script that uses every item above: setup login, SharedArray users, correlation of an ID, tagged requests, a group per step, a custom Trend with a threshold and a handleSummary JSON output. Run it with 1 VU, then 20, then with a ramping scenario, and read the summary each time. If you can explain the script line by line, you can answer most k6 scripting questions. The scenario-based k6 questions take this further into workload design, and our post on shift-left performance testing explains where these tests fit in a pipeline.

We teach performance testing as part of our DevOps training, at the Kharadi, Pune classroom and live online.

FAQ

What language are k6 scripts written in?

JavaScript. TypeScript is also supported. The k6 runtime is not Node.js, so Node-only modules do not work.

Can init code call an API?

No. The k6 docs say init code cannot make HTTP requests. Use setup() for one-time calls.

Where must a SharedArray be created?

In init code. Creating it elsewhere throws an error.

How do I read environment variables in k6?

Through __ENV, with values passed by -e NAME=value or set in the shell.

Does handleSummary remove the default summary?

Yes. Import textSummary from the k6 jslib if you want the default text as well.

What is the default setup timeout?

60 seconds, set by the setupTimeout option.

References

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0
Mridul I am a passionate technology enthusiast with a strong focus on DevOps, Cloud Computing, and Cybersecurity. Through my blogs at DevOps Training Institute, I aim to simplify complex concepts and share practical insights for learners and professionals. My goal is to empower readers with knowledge, hands-on tips, and industry best practices to stay ahead in the ever-evolving world of DevOps.