Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 36 ยท Results and Metrics

Sub-metrics, Cardinality and Per-Route Results in k6

Slice k6 results with request tags, test-wide tags, group() and sub-metrics, keep URL cardinality under control and set per-endpoint thresholds that show which route is slow.

For the basics of tags and group() see Groups and Tags; this lesson goes deeper into reading results per route.

A single http_req_duration for the whole test is like a single temperature for a whole hospital. It tells you something is off but not where. k6 solves this with tags: key-value labels attached to every metric sample. Once samples are tagged you can filter, group and set thresholds on any slice.

Honesty note. k6 cannot run on this site. Script snippets are read-only. The runnable blocks are Node stand-ins that group simulated samples by tag so you can see the idea and the cardinality problem.

Built-in tags

k6 attaches system tags to samples automatically. The ones you will use most:

Tag Example Meaning
name https://shop.example.test/items/17 Defaults to the URL; you can override it
url the full URL The actual request URL
method GET HTTP verb
status 200 Response status
scenario checkout Which scenario produced the sample
group ::login Group path (see below)
expected_response true Status was in the expected range
check status is 200 Name of the check (on checks samples)

You can see them in JSON output and in Prometheus/InfluxDB exports. Not every tag is enabled for every output; the systemTags option controls which ones k6 keeps.

Request tags and the name tag

You add your own tags in params:

JavaScript
import http from 'k6/http';

export default function () {
  http.get('https://shop.example.test/api/search?q=pen', {
    tags: { name: 'Search', feature: 'catalog' },
  });
  http.get(`https://shop.example.test/api/items/${__ITER}`, {
    tags: { name: 'ItemDetail' },   // one series for every id
  });
}

Overriding name matters because URLs with ids and query strings would otherwise create one series per distinct URL. k6 also provides a helper that builds a tagged URL for you:

JavaScript
import http from 'k6/http';

const id = 17;
http.get(http.url`https://shop.example.test/api/items/${id}`); // name tag becomes .../items/${}

Test-wide tags

Tags on the whole run label every sample, which is invaluable when several runs write to the same dashboard:

JavaScript
export const options = {
  tags: { testid: 'checkout-2024-w12', env: 'staging', build: __ENV.GIT_SHA },
};

From the command line the same thing is k6 run --tag env=staging script.js.

Sub-metrics: thresholds on a slice

A sub-metric is a metric filtered by tags, written as metric{tag:value}:

JavaScript
export const options = {
  thresholds: {
    http_req_duration: ['p(95)<500'],                        // everything
    'http_req_duration{name:Search}': ['p(95)<300'],         // just search
    'http_req_duration{name:ItemDetail}': ['p(95)<200'],
    'http_req_duration{expected_response:true}': ['p(95)<400'], // successful requests only
  },
};

Two details trip people up. First, k6 only computes a sub-metric if a threshold mentions it. If you only want it displayed, add a harmless threshold such as ['max>=0']. Second, a threshold on a tag that no sample carries (a typo in the tag name) never fails: always confirm the sub-metric appears in the summary.

Filtering by expected_response:true is a classic best practice: fast error responses (a 500 in 5 ms) should not drag the latency percentiles of successful requests down.

Node.js Stand-in: grouping samples by tag to find the slow route

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.

Groups

group() wraps a block of requests under a name. It is good for sectioning a journey into steps (login, browse, checkout) and it adds the group tag and a group_duration Trend:

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

export default function () {
  group('login', () => {
    const r = http.post(`${BASE}/login`, creds);
    check(r, { 'logged in': (x) => x.status === 200 });
  });

  group('checkout', () => {
    group('add to cart', () => { http.post(`${BASE}/cart`, item); });
    group('pay', () => { http.post(`${BASE}/pay`, card); });
  });
}

Nested groups produce the tag ::checkout::pay. Two warnings from the k6 documentation's spirit:

  • group() does not accept async functions, so it cannot wrap browser test code or other await calls.
  • Group tags make thresholds easy (http_req_duration{group:::checkout}), but a pile of deeply nested groups makes results hard to read. Often the name tag plus a custom metric does the job with less ceremony.

Cardinality: the quiet killer

Every unique combination of tag values is a separate time series. Tagging by user id with 10,000 virtual users or leaving the full URL as name with a million product ids multiplies series, which means more memory in k6, bigger output files and slow dashboards. k6 stops tracking sub-metrics beyond a limit, and some backends reject the data outright.

Rules of thumb:

  1. Tag with categories (route, feature, region), never with identifiers.
  2. Always set name for URLs with variable parts.
  3. Count how many series you create: tags ร— values. Keep it in the low hundreds.
  4. Use systemTags to drop tags you do not need (for example url in huge tests).
Node.js Stand-in: counting series shows why ids are bad tags

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.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should you set the name tag for requests like /items/17 and /items/18?

    By default name is the URL. Variable URLs would create a separate series for each, increasing memory and output size.
  2. 2. What does the threshold key 'http_req_duration{expected_response:true}' filter on?

    expected_response is true when the status was in the expected range, so error responses are excluded from the percentile.
  3. 3. Which is a limitation of group()?

    group() takes a synchronous function; wrapping async code is not supported.
  4. 4. Which tag is the worst idea for a 10,000-user test?

    A unique id per user creates thousands of series. Tag with bounded categories instead.

Summary

  • Tags label every sample; use name for dynamic URLs and test-wide tags for run metadata.
  • Sub-metrics (metric{tag:value}) let thresholds target a slice; they exist only if a threshold references them.
  • group() structures a journey but is synchronous only.
  • Control cardinality: tag with categories, not ids.

Next: End-of-test Summary and Outputs