k6 Scenarios and Thresholds: SLO-Driven Load Testing

k6 Scenarios and Thresholds: SLO-Driven Load Testing
  • k6 scenarios define distinct load profiles (ramp-up, spike, soak) in a single test file
  • Thresholds are pass/fail criteria tied directly to metrics — when they fail, k6 exits non-zero
  • CI gates use threshold failure to block deployments that regress performance
  • Custom metrics let you track business-level indicators alongside HTTP latency
  • Practical examples cover an e-commerce API under realistic traffic patterns

Performance Testing That Actually Gates Deployments

Most load testing workflows produce a report. Someone looks at it, decides the numbers look acceptable, and the deployment continues. This is better than nothing, but it puts a human in a feedback loop that could be automated. k6 thresholds remove that human from the loop: you define acceptable latency and error rate bounds in code, k6 evaluates them during the test run, and the process exits with code 1 if any threshold fails. CI treats that as a build failure.

This post covers k6's scenario system — which defines how load is applied — and the threshold system — which defines what constitutes passing. Together they form the foundation of SLO-driven load testing.


k6 Scenario Types

A k6 script without explicit scenarios uses a single default executor: ramp up to a target VU count, hold, ramp down. Scenarios let you define multiple, independently scheduled load profiles in one test file.

Every scenario requires an executor field. Here are the most useful ones.

ramping-vus

The classic ramp: gradually increase virtual users, hold at peak, ramp back down.

export const options = {
  scenarios: {
    ramp_up: {
      executor: 'ramping-vus',
      startVUs: 0,
      stages: [
        { duration: '2m', target: 50 },   // ramp up to 50 VU over 2 minutes
        { duration: '5m', target: 50 },   // hold 50 VU for 5 minutes
        { duration: '1m', target: 0 },    // ramp down
      ],
    },
  },
};

Use this for baseline performance testing: does the system hold up under gradually increasing load?

constant-arrival-rate

Maintains a fixed request rate (iterations per second) regardless of how many VUs are needed. This is closer to real traffic, which arrives at a consistent rate rather than varying with the number of concurrent users.

export const options = {
  scenarios: {
    steady_traffic: {
      executor: 'constant-arrival-rate',
      rate: 100,              // 100 iterations per second
      timeUnit: '1s',
      duration: '10m',
      preAllocatedVUs: 50,    // VU pool — k6 adds more if needed
      maxVUs: 200,
    },
  },
};

Use this when you know your expected QPS (e.g., "our API handles 100 req/s in production") and want to verify latency at that rate.

ramping-arrival-rate

Like constant-arrival-rate but with configurable stages — useful for ramping up QPS over time:

export const options = {
  scenarios: {
    ramp_qps: {
      executor: 'ramping-arrival-rate',
      startRate: 10,
      timeUnit: '1s',
      stages: [
        { duration: '3m', target: 50 },
        { duration: '5m', target: 100 },
        { duration: '2m', target: 200 },  // stress phase
        { duration: '2m', target: 50 },   // recovery
      ],
      preAllocatedVUs: 100,
      maxVUs: 500,
    },
  },
};

per-vu-iterations

Each VU runs exactly N iterations. Useful for reproducible, fixed-volume tests:

export const options = {
  scenarios: {
    fixed_volume: {
      executor: 'per-vu-iterations',
      vus: 20,
      iterations: 100,    // each of 20 VUs runs 100 iterations = 2000 total
      maxDuration: '5m',
    },
  },
};

shared-iterations

Like per-vu-iterations but distributes the total iteration count across all VUs dynamically:

export const options = {
  scenarios: {
    total_volume: {
      executor: 'shared-iterations',
      vus: 20,
      iterations: 2000,   // 20 VUs share 2000 iterations
      maxDuration: '5m',
    },
  },
};

Combining Multiple Scenarios

Scenarios can run simultaneously with different timing:

export const options = {
  scenarios: {
    browse: {
      executor: 'constant-arrival-rate',
      rate: 100,
      timeUnit: '1s',
      duration: '10m',
      preAllocatedVUs: 50,
      exec: 'browseProducts',   // function to execute
    },
    checkout: {
      executor: 'constant-arrival-rate',
      rate: 10,
      timeUnit: '1s',
      duration: '10m',
      preAllocatedVUs: 20,
      exec: 'checkoutFlow',
      startTime: '1m',          // start 1 minute into the test
    },
  },
};

export function browseProducts() {
  http.get('https://api.example.com/products');
}

export function checkoutFlow() {
  // multi-step checkout scenario
}

This models realistic traffic mix: 10x more browse traffic than checkout traffic.


Defining Thresholds Tied to SLOs

Thresholds are pass/fail expressions evaluated against k6's built-in metrics. If a threshold fails, k6 exits with a non-zero code after the test run completes (or immediately, if you set abortOnFail).

Built-in Metrics Available for Thresholds

Metric What it measures
http_req_duration End-to-end response time
http_req_failed Rate of failed HTTP requests
http_req_waiting Time to first byte (TTFB)
http_reqs Total request count and rate
iterations Scenario iteration count and rate
vus Current active virtual users
vus_max Peak VU count

Basic Threshold Syntax

export const options = {
  thresholds: {
    // 95th percentile response time must be below 300ms
    'http_req_duration': ['p(95)<300'],

    // 99th percentile must be below 1000ms
    'http_req_duration': ['p(95)<300', 'p(99)<1000'],

    // Error rate must be below 1%
    'http_req_failed': ['rate<0.01'],

    // Average must be below 150ms
    'http_req_duration': ['avg<150'],
  },
};

Per-Scenario Thresholds with Tags

Apply thresholds to specific scenarios or URLs using tags:

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

export const options = {
  scenarios: {
    browse: { executor: 'constant-arrival-rate', rate: 100, timeUnit: '1s', duration: '5m', preAllocatedVUs: 50 },
    checkout: { executor: 'constant-arrival-rate', rate: 10, timeUnit: '1s', duration: '5m', preAllocatedVUs: 20 },
  },
  thresholds: {
    // Global: all requests
    'http_req_duration': ['p(95)<500'],

    // Tag: only requests tagged with name="browse"
    'http_req_duration{name:browse}': ['p(95)<200'],

    // Tag: checkout flow gets a more lenient threshold
    'http_req_duration{name:checkout}': ['p(95)<800'],

    // Error rate per endpoint
    'http_req_failed{name:browse}': ['rate<0.005'],
    'http_req_failed{name:checkout}': ['rate<0.001'],
  },
};

export function browseProducts() {
  http.get('https://api.example.com/products', { tags: { name: 'browse' } });
}

export function checkoutFlow() {
  http.post(
    'https://api.example.com/orders',
    JSON.stringify({ productId: 'prod_001', qty: 1 }),
    { tags: { name: 'checkout' }, headers: { 'Content-Type': 'application/json' } }
  );
}

Abort on Threshold Failure

To stop a test immediately when a threshold fails (rather than continuing to completion):

export const options = {
  thresholds: {
    'http_req_duration': [
      { threshold: 'p(99)<2000', abortOnFail: true, delayAbortEval: '10s' }
    ],
    'http_req_failed': [
      { threshold: 'rate<0.05', abortOnFail: true, delayAbortEval: '30s' }
    ],
  },
};

delayAbortEval waits N seconds before evaluating — prevents a single slow burst from terminating the test prematurely.


Pass/Fail Gates in CI

k6 exits with code 0 when all thresholds pass and 1 when any fail. CI systems interpret this automatically.

GitHub Actions

name: Performance Tests

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  k6:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4

      - name: Install k6
        run: |
          sudo gpg -k
          sudo gpg --no-default-keyring \
            --keyring /usr/share/keyrings/k6-archive-keyring.gpg \
            --keyserver hkp://keyserver.ubuntu.com:80 \
            --recv-keys C5AD17C747E3415A3642D57D77C6C491D6AC1D69
          echo "deb [signed-by=/usr/share/keyrings/k6-archive-keyring.gpg] \
            https://dl.k6.io/deb stable main" \
            | sudo tee /etc/apt/sources.list.d/k6.list
          sudo apt-get update && sudo apt-get install k6

      - name: Run k6 load test
        run: k6 run --out json=/tmp/k6-results.json load-test.js
        env:
          BASE_URL: ${{ vars.STAGING_API_URL }}
          API_KEY: ${{ secrets.STAGING_API_KEY }}

      - name: Upload results
        uses: actions/upload-artifact@v4
        if: always()
        with:
          name: k6-results
          path: /tmp/k6-results.json

The k6 run step fails the workflow if any threshold is violated — no extra scripting required.

Outputting Results to Grafana Cloud

For persistent result storage and dashboards:

k6 run \
  --out cloud \
  load-test.js

Or for self-hosted Grafana with InfluxDB:

k6 run \
  --out influxdb=http://localhost:8086/k6 \
  load-test.js

Grafana dashboards over InfluxDB let you overlay load test results from multiple runs, track p95 trend over weeks, and correlate performance degradation with specific deployments.


Custom Metrics with k6

Built-in metrics cover HTTP layer performance. Custom metrics capture business-level indicators.

Counter — Count Events

import { Counter } from 'k6/metrics';

const checkoutErrors = new Counter('checkout_errors');

export function checkoutFlow() {
  const res = http.post('/orders', payload);
  if (res.status !== 201) {
    checkoutErrors.add(1);
  }
}

export const options = {
  thresholds: {
    'checkout_errors': ['count<10'],  // fail if more than 10 checkout errors total
  },
};

Trend — Track Latency of a Specific Operation

import { Trend } from 'k6/metrics';

const dbQueryTime = new Trend('db_query_duration');

export function searchProducts() {
  const start = Date.now();
  const res = http.get('/products/search?q=shoes');
  dbQueryTime.add(Date.now() - start);
}

export const options = {
  thresholds: {
    'db_query_duration': ['p(95)<100'],  // database queries must resolve in < 100ms (p95)
  },
};

Rate — Track Success/Failure Rate

import { Rate } from 'k6/metrics';

const successRate = new Rate('successful_transactions');

export function checkoutFlow() {
  const res = http.post('/orders', payload);
  const success = check(res, {
    'order created': (r) => r.status === 201,
    'order has id': (r) => r.json('id') !== undefined,
  });
  successRate.add(success);
}

export const options = {
  thresholds: {
    'successful_transactions': ['rate>0.99'],  // 99%+ of transactions must succeed
  },
};

Practical Example: E-Commerce API Under Realistic Load

Here is a complete k6 script modeling an e-commerce API with three distinct traffic patterns, per-scenario thresholds, and custom business metrics:

import http from 'k6/http';
import { check, sleep } from 'k6';
import { Rate, Trend } from 'k6/metrics';

const checkoutSuccess = new Rate('checkout_success_rate');
const searchLatency = new Trend('search_latency');

const BASE_URL = __ENV.BASE_URL || 'https://api-staging.example.com';

export const options = {
  scenarios: {
    // 1. Browse traffic — high volume, read-only
    browse: {
      executor: 'ramping-arrival-rate',
      startRate: 20,
      timeUnit: '1s',
      stages: [
        { duration: '2m', target: 100 },
        { duration: '5m', target: 100 },
        { duration: '1m', target: 0 },
      ],
      preAllocatedVUs: 60,
      maxVUs: 200,
      exec: 'browseCatalog',
    },
    // 2. Search traffic — medium volume, DB-heavy
    search: {
      executor: 'constant-arrival-rate',
      rate: 30,
      timeUnit: '1s',
      duration: '8m',
      preAllocatedVUs: 20,
      maxVUs: 80,
      exec: 'searchProducts',
      startTime: '30s',
    },
    // 3. Checkout — low volume, write-heavy, critical path
    checkout: {
      executor: 'constant-arrival-rate',
      rate: 5,
      timeUnit: '1s',
      duration: '8m',
      preAllocatedVUs: 15,
      maxVUs: 40,
      exec: 'completeCheckout',
      startTime: '1m',
    },
  },

  thresholds: {
    // Global SLO: 95% of all requests under 500ms
    'http_req_duration': ['p(95)<500', 'p(99)<1500'],

    // Browse: fast reads, tight threshold
    'http_req_duration{scenario:browse}': ['p(95)<200'],

    // Search: DB-heavy, slightly more lenient
    'http_req_duration{scenario:search}': ['p(95)<400'],

    // Checkout: most lenient, but must succeed
    'http_req_duration{scenario:checkout}': ['p(95)<800'],

    // Error rate: near-zero
    'http_req_failed': ['rate<0.01'],

    // Business metric: 99%+ checkout success
    'checkout_success_rate': ['rate>0.99'],

    // Search latency custom metric
    'search_latency': ['p(95)<350'],
  },
};

export function browseCatalog() {
  const res = http.get(`${BASE_URL}/products?page=1&limit=20`, {
    tags: { scenario: 'browse' },
  });
  check(res, { 'products returned': (r) => r.status === 200 });
  sleep(1);
}

export function searchProducts() {
  const terms = ['shoes', 'jacket', 'running', 'sale', 'new arrivals'];
  const term = terms[Math.floor(Math.random() * terms.length)];

  const start = Date.now();
  const res = http.get(`${BASE_URL}/products/search?q=${term}`, {
    tags: { scenario: 'search' },
  });
  searchLatency.add(Date.now() - start);

  check(res, {
    'search returned 200': (r) => r.status === 200,
    'search has results': (r) => r.json('total') > 0,
  });
  sleep(0.5);
}

export function completeCheckout() {
  const authRes = http.post(
    `${BASE_URL}/auth/token`,
    JSON.stringify({ client_id: 'test', client_secret: __ENV.API_KEY }),
    { headers: { 'Content-Type': 'application/json' }, tags: { scenario: 'checkout' } }
  );

  if (authRes.status !== 200) {
    checkoutSuccess.add(false);
    return;
  }

  const token = authRes.json('access_token');
  const headers = {
    Authorization: `Bearer ${token}`,
    'Content-Type': 'application/json',
  };

  const orderRes = http.post(
    `${BASE_URL}/orders`,
    JSON.stringify({ items: [{ sku: 'SKU-001', qty: 1 }] }),
    { headers, tags: { scenario: 'checkout' } }
  );

  const success = check(orderRes, {
    'order created': (r) => r.status === 201,
    'order has id': (r) => r.json('id') !== undefined,
  });

  checkoutSuccess.add(success);
  sleep(2);
}

Running this against staging before each release tells you, with a binary yes/no answer, whether the deployment meets your SLOs. No report interpretation required.


Reading k6 Output

At the end of a run, k6 prints each metric with its threshold status:

✓ http_req_duration............: avg=87ms   min=12ms   med=73ms   max=1.2s  p(90)=180ms p(95)=240ms
✗ http_req_duration{scenario:checkout}: avg=650ms  min=120ms  med=590ms  max=3.1s  p(90)=980ms p(95)=1.1s
  ↳ 94% — ✓ 4712 / ✗ 288
✓ http_req_failed.............: 0.42% ✓ 5000 ✗ 21
✗ checkout_success_rate........: 97.30% ✓ 4860 ✗ 140

A ✗ on any threshold fails the run. In CI this translates directly to a failed build step without any additional scripting.


Wrapping Up

k6's scenario system gives you fine-grained control over how load is shaped — ramp patterns, arrival rates, traffic mix, and timing. The threshold system converts load test results from descriptive (here are the numbers) to prescriptive (these are the bounds you must stay within). Together they create a performance gate that is as automated and unambiguous as any unit test.

The key discipline is anchoring thresholds to real SLOs — not arbitrary round numbers, but commitments you have made to users (or would be embarrassed to breach). When thresholds reflect actual SLOs, a failing threshold is not a flaky test to silence; it is a signal that a deployment should not ship.

Read more

Start now free