Add thresholds to your script

Thresholds turn your baseline numbers into automated pass/fail criteria. When a threshold is breached, k6 exits with a non-zero exit code, which means you can integrate baseline enforcement into CI/CD pipelines. This is the second key technical milestone that many new users skip. Without thresholds, your test only reports numbers but never fails.

To add thresholds to your baseline script, complete the following steps:

  1. Open baseline.js and add a thresholds property to the options object:

    JavaScript
    export const options = {
      stages: [
        { duration: '30s', target: 20 },
        { duration: '1m', target: 20 },
        { duration: '30s', target: 0 },
      ],
      thresholds: {
        http_req_duration: ['p(95)<500'],
        http_req_failed: ['rate<0.01'],
      },
    };

    Each threshold is a metric name mapped to an array of conditions. The p(95)<500 condition means the test fails if more than 5% of requests take longer than 500 ms. The rate<0.01 condition means the test fails if more than 1% of requests return errors.

  2. You can also add thresholds on your checks to ensure correctness stays above a minimum rate:

    JavaScript
    thresholds: {
      http_req_duration: ['p(95)<500'],
      http_req_failed: ['rate<0.01'],
      checks: ['rate>0.99'],
    },

    The checks threshold fails the test if the overall check pass rate drops below 99%.

  3. Save the file. Your complete baseline.js should now look like this:

    JavaScript
    import http from 'k6/http';
    import { check, sleep } from 'k6';
    
    export const options = {
      stages: [
        { duration: '30s', target: 20 },
        { duration: '1m', target: 20 },
        { duration: '30s', target: 0 },
      ],
      thresholds: {
        http_req_duration: ['p(95)<500'],
        http_req_failed: ['rate<0.01'],
        checks: ['rate>0.99'],
      },
    };
    
    export default function () {
      const res = http.get('https://quickpizza.grafana.com');
    
      check(res, {
        'status is 200': (r) => r.status === 200,
        'response body is not empty': (r) => r.body.length > 0,
      });
    
      sleep(1);
    }

    Note

    You can define multiple conditions per metric. For example, http_req_duration: ['p(95)<500', 'p(99)<1000'] requires both the p95 and p99 to stay within their respective limits.

In the next milestone, you validate that your thresholds work by running the test and checking the exit code.

More to explore (optional)

At this point in your path, you can explore the following topics:

Thresholds

Inspect thresholds in Grafana Cloud k6


page 7 of 10