Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 36 ยท Protocols and APIs

Batches, Cookies and Redirects in k6

Load a page and its assets in parallel with http.batch, manage cookies with the cookie jar, control redirects and expected statuses, and know when parallelism helps or hurts.

A real browser never fetches one URL and stops. It loads a page, then its scripts, styles and API calls in parallel, and it keeps cookies between requests. k6 gives you matching tools: http.batch() for parallel requests, a cookie jar per virtual user, and options for redirects and what counts as a failure.

Honesty note. k6 itself cannot run on this site. The js blocks with k6/http imports are read-only. Runnable blocks are Node stand-ins that reproduce the behaviour so you can see the effect.

Parallel requests with http.batch

http.batch() takes an array (or an object) of requests and sends them in parallel, up to a per-VU limit (batch option, default 20; batchPerHost default 6). It returns when all responses are in.

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

export default function () {
  const responses = http.batch([
    ['GET', 'https://shop.example.test/api/products', null, { tags: { name: 'products' } }],
    ['GET', 'https://shop.example.test/api/cart', null, { tags: { name: 'cart' } }],
    { method: 'GET', url: 'https://shop.example.test/api/offers' },
  ]);
  check(responses[0], { 'products ok': (r) => r.status === 200 });
}

Each entry can be an array [method, url, body, params], an object { method, url, body, params }, or just a URL string (GET). With an object of named requests you get an object of named responses, which reads better:

JavaScript
const res = http.batch({
  products: 'https://shop.example.test/api/products',
  cart: { method: 'GET', url: 'https://shop.example.test/api/cart' },
});
console.log(res.products.status, res.cart.status);

When to batch

Batch requests that a browser would issue at the same time: assets of one page, independent API calls fired by a single screen. Do not batch requests that depend on each other (a login and the call that needs its token), and do not batch just to push more load: a batch of ten requests from one VU is ten simultaneous connections, which changes your model. More on that in Test design and workload models.

Node.js Stand-in: sequential versus parallel requests

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.

Every VU has its own cookie jar, and cookies set by Set-Cookie are sent automatically on later requests to the same domain, just like a browser. That means a login flow usually "just works":

JavaScript
import http from 'k6/http';

export default function () {
  http.post('https://app.example.test/login', { user: 'ana', pass: 'secret' });
  const res = http.get('https://app.example.test/account'); // session cookie sent
  console.log(res.status);
}

You can inspect and edit the jar directly:

JavaScript
const jar = http.cookieJar();
jar.set('https://app.example.test', 'ab_group', 'B');           // add a cookie
const cookies = jar.cookiesForURL('https://app.example.test'); // { ab_group: ['B'], ... }

// A one-off jar for a single request:
const fresh = new http.CookieJar();
http.get('https://app.example.test/', { jar: fresh });

// Per-request cookies:
http.get('https://app.example.test/', { cookies: { consent: 'yes' } });

The jar is reset at the start of each iteration, so cookies do not leak from one simulated visitor to the next. If you need a session to last across iterations, log in during setup() and share the token, or log in at the start of every iteration (the more realistic choice when each iteration represents one visitor).

Node.js Stand-in: a cookie jar that follows Set-Cookie

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.

Redirects

k6 follows up to 10 redirects by default for GET/HEAD-style flows. You can change that globally or per request:

JavaScript
export const options = { maxRedirects: 0 }; // never follow

const res = http.get('https://app.example.test/old', { redirects: 0 });
console.log(res.status, res.headers['Location']);

Turning redirects off is useful when you want to measure the redirect response itself or when a login returns a 302 with a token in the Location header that you want to parse.

Expected statuses

By default k6 marks responses with status 200 to 399 as successful for the built-in http_req_failed metric. If your API legitimately returns 404 or 409 in some scenarios, tell k6 so failures are not overcounted:

JavaScript
import http from 'k6/http';

// Globally (init stage):
http.setResponseCallback(http.expectedStatuses({ min: 200, max: 299 }, 404));

// Or for a single request:
http.get('https://app.example.test/items/999', {
  responseCallback: http.expectedStatuses(404),
});

A response outside the expected set increments http_req_failed; you can then put a threshold on it (see Built-in metrics).

Other request settings worth knowing

  • insecureSkipTLSVerify: true in options for self-signed staging certificates.
  • userAgent, http.setResponseCallback, discardResponseBodies (a global way to save memory).
  • noConnectionReuse and noVUConnectionReuse to simulate fresh connections for each request (expensive, but sometimes realistic).
  • hosts to override DNS for a test, for example sending shop.example.test to a staging IP.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does http.batch() do?

    Batched requests run concurrently (within the batch limits) and the call returns after every response is available.
  2. 2. When should you NOT put two requests in the same batch?

    A batch sends everything at once, so a request that depends on an earlier response (for example a login token) must be a separate call.
  3. 3. How do you stop k6 from following a 302 redirect for one request?

    The redirects param (or the maxRedirects option globally) limits how many redirects k6 follows; 0 means none.
  4. 4. Your API returns 404 on purpose in one scenario. How do you avoid counting it as a failed request?

    expectedStatuses tells k6 which codes are normal, so only other codes increase http_req_failed.

Summary

  • http.batch() runs requests in parallel; use it for independent calls such as a page's assets.
  • Each VU has a cookie jar that is reset every iteration; use http.cookieJar() to edit it.
  • redirects and maxRedirects control redirect following.
  • http.expectedStatuses() defines what counts as a failed request.

Next: WebSockets and gRPC