k6 Custom Metrics and Extensions: Beyond Built-in Counters
k6's built-in metrics cover HTTP response times, request rates, and error counts. They're useful for most load tests. But real-world performance testing often needs more: tracking business metrics (orders per second, auth success rate), measuring custom timings (time-to-first-byte vs time-to-full-response), or instrumenting application-level events that don't map to HTTP requests.
k6 provides four custom metric types and an extension system (xk6) for cases where the built-in metrics and protocol support aren't enough. This guide covers all of it.
The Four Custom Metric Types
k6's custom metric types mirror the types you'd find in Prometheus or StatsD.
Counter
A counter is a cumulative value that only increases. Use it for: total requests, error count, events processed, items created.
import { Counter } from 'k6/metrics';
import http from 'k6/http';
const errors = new Counter('api_errors');
const ordersCreated = new Counter('orders_created');
export default function () {
const res = http.post('https://api.example.com/orders', JSON.stringify({
product_id: 'prod_123',
quantity: 1,
}), {
headers: { 'Content-Type': 'application/json' },
});
if (res.status === 201) {
ordersCreated.add(1);
} else {
errors.add(1, { endpoint: 'POST /orders', status: res.status.toString() });
}
}The second argument to .add() is a tag object. Tags let you slice the metric in reports and dashboards.
Gauge
A gauge tracks the current value — it can go up or down. Use it for: current queue depth, active sessions, in-flight requests.
import { Gauge } from 'k6/metrics';
import http from 'k6/http';
const queueDepth = new Gauge('queue_depth');
export default function () {
const statusRes = http.get('https://api.example.com/queue/status');
const status = statusRes.json();
if (status.queue_depth !== undefined) {
queueDepth.add(status.queue_depth);
}
}Rate
A rate tracks what percentage of values are non-zero (truthy). Use it for: cache hit rate, auth success rate, validation pass rate.
import { Rate } from 'k6/metrics';
import http from 'k6/http';
const cacheHitRate = new Rate('cache_hit_rate');
const authSuccessRate = new Rate('auth_success_rate');
export default function () {
const res = http.get('https://api.example.com/api/products/123', {
headers: { Authorization: `Bearer ${__ENV.TOKEN}` },
});
// Track cache hits via header
const hit = res.headers['X-Cache'] === 'HIT';
cacheHitRate.add(hit);
// Track auth success
authSuccessRate.add(res.status !== 401);
}Rate metrics report as a fraction (0.0–1.0) in the summary.
Trend
A trend collects a series of values and reports min, max, average, and percentiles. Use it for: custom timing measurements, payload sizes, database query times.
import { Trend } from 'k6/metrics';
import http from 'k6/http';
const timeToFirstByte = new Trend('time_to_first_byte', true); // true = milliseconds
const dbQueryTime = new Trend('db_query_time', true);
export default function () {
const start = Date.now();
const res = http.get('https://api.example.com/api/search?q=test');
// TTFB via timing header (if server sends it)
const ttfb = parseFloat(res.headers['X-Time-To-First-Byte'] || '0');
if (ttfb > 0) {
timeToFirstByte.add(ttfb);
}
// DB query time via response header
const dbTime = parseFloat(res.headers['X-DB-Query-Time'] || '0');
if (dbTime > 0) {
dbQueryTime.add(dbTime);
}
}The second argument to new Trend() flags the metric as a time value, which affects how k6 formats it in output.
Setting Thresholds on Custom Metrics
Custom metrics integrate fully with k6's threshold system:
import { Counter, Rate, Trend } from 'k6/metrics';
import http from 'k6/http';
const errors = new Counter('api_errors');
const successRate = new Rate('api_success_rate');
const customLatency = new Trend('custom_latency', true);
export const options = {
thresholds: {
// Built-in metric
http_req_duration: ['p(99)<500'],
// Custom trend: percentiles work the same way
custom_latency: ['p(95)<200', 'p(99)<500', 'avg<100'],
// Custom rate: must stay above 99%
api_success_rate: ['rate>0.99'],
// Custom counter: tagged threshold — errors on /orders endpoint
'api_errors{endpoint:POST /orders}': ['count<10'],
},
};
export default function () {
const start = Date.now();
const res = http.post('https://api.example.com/orders', '{}', {
headers: { 'Content-Type': 'application/json' },
});
const duration = Date.now() - start;
customLatency.add(duration);
successRate.add(res.status < 400);
if (res.status >= 400) {
errors.add(1, { endpoint: 'POST /orders' });
}
}When a threshold fails, k6 exits with a non-zero status code — which fails CI builds.
Tags and Tag Filtering
Tags allow you to annotate metric samples and filter them in thresholds:
// Set tags for the current iteration
import { group, check } from 'k6';
export default function () {
group('checkout flow', () => {
// All metrics inside group() get tagged with group:'checkout flow'
const res = http.get('https://api.example.com/cart');
check(res, { 'cart loaded': (r) => r.status === 200 });
});
}Tag-filtered thresholds:
export const options = {
thresholds: {
// Only check latency for requests tagged with the checkout group
'http_req_duration{group:::checkout flow}': ['p(95)<300'],
// Different threshold for different URLs
'http_req_duration{url:https://api.example.com/checkout}': ['p(99)<500'],
},
};Measuring Business Metrics
Business metrics tell you whether your application is functioning correctly under load, not just whether it's fast. A response time of 50ms means nothing if 30% of checkout requests are silently failing:
import { Rate, Counter, Trend } from 'k6/metrics';
import http from 'k6/http';
const checkoutSuccess = new Rate('checkout_success_rate');
const orderValue = new Trend('order_value_dollars');
const paymentErrors = new Counter('payment_errors');
export const options = {
thresholds: {
checkout_success_rate: ['rate>0.995'],
'payment_errors{type:timeout}': ['count<5'],
},
};
export default function () {
const cart = http.get('https://api.example.com/cart', {
headers: { Authorization: `Bearer ${__ENV.TOKEN}` },
});
const cartData = cart.json();
const order = http.post(
'https://api.example.com/checkout',
JSON.stringify({ cart_id: cartData.id }),
{ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${__ENV.TOKEN}` } }
);
const success = order.status === 201;
checkoutSuccess.add(success);
if (success) {
const orderData = order.json();
orderValue.add(orderData.total_cents / 100);
} else {
const error = order.json();
const errorType = error.code || 'unknown';
paymentErrors.add(1, { type: errorType });
}
}Custom Timing with k6/execution
For timing specific code sections rather than full HTTP request durations:
import { Trend } from 'k6/metrics';
import http from 'k6/http';
const jsonParseTime = new Trend('json_parse_time', true);
const totalProcessingTime = new Trend('total_processing_time', true);
export default function () {
const res = http.get('https://api.example.com/api/large-dataset');
const parseStart = Date.now();
const data = res.json();
jsonParseTime.add(Date.now() - parseStart);
const processStart = Date.now();
const processed = data.items.filter(item => item.active).map(item => item.id);
totalProcessingTime.add(Date.now() - processStart);
// Use processed data in subsequent requests
if (processed.length > 0) {
http.get(`https://api.example.com/api/items/${processed[0]}`);
}
}xk6: Building Custom Extensions
xk6 lets you extend k6 with Go packages — new protocol support, custom output formats, or access to native libraries that JavaScript can't reach. Common use cases: gRPC testing, Kafka producers, custom output to Datadog, database connections.
Installing xk6
go install go.k6.io/xk6/cmd/xk6@latestBuilding k6 with Extensions
# Build k6 with the SQL extension
xk6 build --with github.com/grafana/xk6-sql
# Build with multiple extensions
xk6 build \
--with github.com/grafana/xk6-sql \
--with github.com/grafana/xk6-browser \
--with github.com/nicholasgasior/xk6-kafka
# Specify output binary name
xk6 build --output ./k6-custom \
--with github.com/grafana/xk6-sqlRun your custom binary:
./k6 run test.js
# or
./k6-custom run test.jsUsing the xk6-sql Extension
import sql from 'k6/x/sql';
import http from 'k6/http';
import { check } from 'k6';
const db = sql.open('postgres', __ENV.DATABASE_URL);
export function setup() {
// Seed test data
db.exec('INSERT INTO test_users (email) VALUES ($1) ON CONFLICT DO NOTHING',
['load-test@example.com']);
}
export default function () {
// Test HTTP API
const res = http.get('https://api.example.com/api/users', {
headers: { Authorization: `Bearer ${__ENV.TOKEN}` },
});
check(res, { 'status 200': (r) => r.status === 200 });
// Verify DB state directly
const rows = db.query('SELECT COUNT(*) as count FROM users WHERE created_at > NOW() - INTERVAL \'1 minute\'');
// Process rows...
}
export function teardown() {
db.close();
}Using xk6-browser for Real User Metrics
import { chromium } from 'k6/experimental/browser';
import { Trend } from 'k6/metrics';
const pageLoadTime = new Trend('page_load_time', true);
const lcp = new Trend('largest_contentful_paint', true);
export const options = {
scenarios: {
browser: {
executor: 'constant-vus',
exec: 'browserTest',
vus: 2,
duration: '30s',
options: {
browser: { type: 'chromium' },
},
},
},
};
export async function browserTest() {
const browser = chromium.launch({ headless: true });
const page = browser.newPage();
try {
const startTime = Date.now();
await page.goto('https://example.com/dashboard');
await page.waitForSelector('[data-testid="dashboard-loaded"]');
pageLoadTime.add(Date.now() - startTime);
// Web Vitals
const lcpValue = await page.evaluate(() => {
return new Promise(resolve => {
new PerformanceObserver(list => {
const entries = list.getEntries();
resolve(entries[entries.length - 1].startTime);
}).observe({ entryTypes: ['largest-contentful-paint'] });
// Fallback after 3s
setTimeout(() => resolve(0), 3000);
});
});
if (lcpValue > 0) {
lcp.add(lcpValue);
}
} finally {
page.close();
browser.close();
}
}Outputting Metrics to External Systems
Prometheus (via Prometheus Remote Write)
k6 run --out experimental-prometheus-rw test.jsexport const options = {
ext: {
loadimpact: {
projectID: 123456,
},
},
};Or via environment variable:
K6_PROMETHEUS_RW_SERVER_URL=http://localhost:9090/api/v1/write \
k6 run --out experimental-prometheus-rw test.jsInfluxDB
k6 run --out influxdb=http://localhost:8086/k6 test.jsCustom tags for InfluxDB queries:
export const options = {
ext: {
influxdb: {
addr: 'http://localhost:8086',
db: 'k6',
},
},
tags: {
environment: 'staging',
version: __ENV.APP_VERSION || 'unknown',
},
};JSON Output for Custom Pipelines
k6 run --out json=results.json test.jsEach line is a JSON object — a metric sample or event. Parse it for custom analysis:
# Extract all p99 latency samples
cat results.json | jq 'select(.type=="Point" and .metric=="http_req_duration") | .data.value' | \
sort -n | awk 'BEGIN{c=0}{a[c++]=$1}END{print a[int(c*0.99)]}'Summary Output Customization
Override k6's end-of-run summary with handleSummary:
import { textSummary } from 'https://jslib.k6.io/k6-summary/0.0.2/index.js';
export function handleSummary(data) {
const p99 = data.metrics.http_req_duration.values['p(99)'];
const successRate = data.metrics.http_req_failed ?
1 - data.metrics.http_req_failed.values.rate : 1;
const passed = p99 < 500 && successRate > 0.99;
return {
stdout: textSummary(data, { indent: ' ', enableColors: true }),
'results/summary.json': JSON.stringify({
passed,
p99_ms: Math.round(p99),
success_rate: successRate,
rps: Math.round(data.metrics.http_reqs.values.rate),
timestamp: new Date().toISOString(),
}, null, 2),
'results/summary.txt': `
Load Test Result: ${passed ? 'PASS' : 'FAIL'}
P99 Latency: ${Math.round(p99)}ms (threshold: 500ms)
Success Rate: ${(successRate * 100).toFixed(2)}% (threshold: 99%)
RPS: ${Math.round(data.metrics.http_reqs.values.rate)}
`.trim(),
};
}The handleSummary return value maps filenames to content. stdout goes to the terminal. Other keys write files. This is how you generate CI-friendly artifacts without post-processing scripts.
Common Patterns
Parameterized user data: Load test data from CSV so each virtual user has unique credentials or inputs:
import { SharedArray } from 'k6/data';
import papaparse from 'https://jslib.k6.io/papaparse/5.1.1/index.js';
const users = new SharedArray('users', function() {
return papaparse.parse(open('./users.csv'), { header: true }).data;
});
export default function () {
const user = users[__VU % users.length];
http.post('https://api.example.com/login', JSON.stringify({
email: user.email,
password: user.password,
}));
}Scenario-specific metrics: Different scenarios can use different custom metrics:
const adminMetrics = {
latency: new Trend('admin_latency', true),
errors: new Counter('admin_errors'),
};
const userMetrics = {
latency: new Trend('user_latency', true),
errors: new Counter('user_errors'),
};
export const options = {
scenarios: {
admin_flow: { exec: 'adminScenario', /* ... */ },
user_flow: { exec: 'userScenario', /* ... */ },
},
};
export function adminScenario() {
const res = http.get('https://api.example.com/admin/dashboard', {
headers: { Authorization: `Bearer ${__ENV.ADMIN_TOKEN}` },
});
adminMetrics.latency.add(res.timings.duration);
if (res.status >= 400) adminMetrics.errors.add(1);
}
export function userScenario() {
const res = http.get('https://api.example.com/dashboard', {
headers: { Authorization: `Bearer ${__ENV.USER_TOKEN}` },
});
userMetrics.latency.add(res.timings.duration);
if (res.status >= 400) userMetrics.errors.add(1);
}Custom metrics transform k6 from a tool that tells you "requests are slow" into one that tells you "checkout is failing for 2% of users and order creation latency spiked at 3:42pm."