Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 36 ยท Checks and Thresholds

Custom Metrics

Create your own k6 metrics with Counter, Gauge, Rate and Trend, record business values such as cart size or login time, tag them, and set thresholds on them.

The built-in metrics describe HTTP behaviour: how long requests took and how many failed. Often the number you care about is something else: how long the whole checkout took, how many orders were created, how many items were in each cart, how often the login step needed a retry. For that, k6 lets you define custom metrics in the k6/metrics module and feed them values from your script. Custom metrics appear in the end-of-test summary, can have thresholds, and are sent to every output (JSON, Grafana, and so on) like any built-in metric.

The four metric types

Type What it records Typical question Summary shows
Counter A running sum that only goes up How many orders did we create? total and per-second rate
Gauge The latest value, with min and max How many items are in the cart right now? last value, min, max
Rate The share of non-zero (true) values What fraction of logins were retries? percentage
Trend A series of numbers with statistics How long did the checkout flow take? avg, min, med, max, percentiles

You create each one in init code (top level), then call .add(value) during iterations.

JavaScript
import http from 'k6/http';
import { Counter, Gauge, Rate, Trend } from 'k6/metrics';

const ordersCreated = new Counter('orders_created');
const cartSize = new Gauge('cart_size');
const retryRate = new Rate('login_retry_rate');
const checkoutTime = new Trend('checkout_flow_ms', true); // true = values are times

export default function () {
  const start = Date.now();

  const login = http.post(`${BASE}/login`, creds);
  retryRate.add(login.status !== 200); // true counts as 1

  const cart = http.get(`${BASE}/cart`).json();
  cartSize.add(cart.items.length);

  const order = http.post(`${BASE}/orders`, null);
  if (order.status === 201) {
    ordersCreated.add(1);
  }

  checkoutTime.add(Date.now() - start);
}

The second argument to new Trend(name, true) tells k6 the values are durations in milliseconds, so the summary formats them as time (1.2s, 340ms) rather than plain numbers.

Tags on custom metrics

.add(value, tags) accepts an optional tags object, so one metric can be broken down:

JavaScript
checkoutTime.add(elapsed, { payment: 'card' });
checkoutTime.add(elapsed, { payment: 'invoice' });

Keep the same rule as for all tags: small, bounded value sets only.

Thresholds on custom metrics

Custom metrics are first-class citizens for thresholds. The allowed aggregations follow their type:

JavaScript
export const options = {
  thresholds: {
    orders_created: ['count>50'],
    login_retry_rate: ['rate<0.02'],
    checkout_flow_ms: ['p(95)<2500'],
    'checkout_flow_ms{payment:card}': ['p(95)<2000'],
  },
};

This is the standard way to enforce business-level SLOs: "95% of checkouts finish within 2.5 seconds".

Metric naming rules

Names must contain only letters, numbers and underscores, start with a letter or underscore, and be at most 128 characters. Choose names that say what and in which unit: checkout_flow_ms, not time2. Defining two metrics with the same name in one script is an error.

A stand-in for the four types

The code below is not k6; it implements tiny versions of Counter, Gauge, Rate and Trend, then uses them against a local API with a flaky login so you can see what each type reports. Rates and counts are deterministic here (the server fails every third login by design); only the trend's timing is variable, so the program prints properties instead of exact milliseconds.

Node.js Stand-in: the four metric types

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.

Two of six logins failed, so the Rate shows 33.3%. The Counter sums, the Gauge keeps extremes, and the Trend keeps every sample so percentiles can be computed.

When to use which

  • Counting events (orders, signups, retries) means Counter.
  • A level that goes up and down (queue length reported by an API) means Gauge.
  • A yes/no outcome whose share matters (cache hit, retry needed) means Rate.
  • Anything measured in time or size where distribution matters means Trend.

Common mistakes

  • Creating a metric inside the default function. It must be in init code.
  • Using a Counter for something that goes down, or a Trend for yes/no values.
  • Forgetting true on a duration Trend, so the summary prints raw milliseconds without units.
  • Adding a user id as a tag on a custom metric (cardinality explosion).
  • Measuring with Date.now() around code that includes sleep(): you will time the pause too. Time only the work.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which metric type fits 'how long did the checkout flow take'?

    Durations are collected in a Trend so that average, median and percentiles can be computed.
  2. 2. Where must custom metrics be created?

    Metrics are declared once in init code; you call .add() inside iterations.
  3. 3. What does new Trend('t', true) change?

    The second argument marks the values as time, so the summary shows units like ms and s.
  4. 4. Which threshold is valid for a Rate metric named login_retry_rate?

    Rate metrics only support the rate aggregation.

Summary

  • Counter, Gauge, Rate and Trend from k6/metrics record your own numbers.
  • Create metrics in init code; call .add(value, tags) in iterations.
  • Mark duration trends with true for readable output.
  • Custom metrics accept thresholds that fit their type, so business SLOs become pass/fail rules.
  • Keep names descriptive and tags bounded.

Next: Think Time and Pacing