Using k6 Thresholds to Validate API SLAs Under Load
Learn how to set and verify API response time and error rate thresholds in k6, integrate them into CI/CD, and ensure reliable performance testing.
04 Aug 2025, 10:15 UTC

Why API SLAs matter under load
When an API is called by many clients at once, response times can drift beyond the promised latency. Manual checks are too slow to catch these regressions before deployment.
Takeaway
The practical advantage of k6 is that you can define quantitative thresholds for latency and error rates, and the test runner will exit with a non‑zero status code the moment any threshold is violated. This makes SLA validation a built‑in gate in CI/CD pipelines.
How k6 thresholds work
k6 supports three built‑in metric categories that can be used for thresholding:
- HTTP request duration – measured per request, configurable as a constant value or an expression such as
p(95). - Error rate – the proportion of requests that return a non‑2xx status code.
- Custom metrics – any metric you emit via the JavaScript API, e.g., request count, queue length.
Thresholds are evaluated in real‑time. The runner aggregates samples according to the aggregation period you choose (default 1 second) and checks the condition after each sample. If the condition fails, the process exits with status 1, which CI systems interpret as a failure.
Defining realistic SLA thresholds
Choosing a threshold starts with the business‑level SLA. Typical API SLAs specify a 95th‑percentile response time of 200 ms and an error rate below 0.1 %. To translate this into a k6 threshold you can write an expression that computes the 95th‑percentile over the aggregation window:
http_req_duration{p95}<200>
Here p95 is a built‑in function that returns the 95th percentile of the recorded durations. The expression <200 means “the 95th‑percentile must stay under 200 ms”. You can also combine multiple conditions with logical operators, for example:
http_req_duration{p95}<200> && http_req_rate<0.001>
Worked example: validating an API endpoint
Below is a minimal k6 script that tests a single endpoint and applies two thresholds. Replace the placeholder URL with your actual endpoint and adjust the threshold values to match your SLA.
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
stages: [
{ duration: '30s', target: 20 },
{ duration: '90s', target: 100 },
{ duration: '30s', target: 0 },
],
thresholds: {
'http_req_duration{p95}': ['p(95)<250'],
'http_req_rate': ['rate<0.005'],
},
};
export default function () {
const res = http.get('https://api.example.com/health');
sleep(1);
}
How to run and verify:
- Save the script as
api_sla.js. - Execute it with the JSON output flag so you can inspect the threshold results later:
k6 run --out json=report.json api_sla.js - Check the process exit status. A non‑zero code means at least one threshold was breached. In a CI job you can capture
$?after the command and fail the build if it is not zero. - Open
report.jsonand locate thethresholdssection. Thep(95)value reported should be compared to the250limit you set. If the reported p(95) exceeds 250 ms, the test failed.
Potential risk: setting the threshold too tight (e.g., p(95)<100) may cause the test to fail even when the service is healthy, generating false positives. Validate the threshold against baseline measurements before integrating it into CI.
Trade‑offs and limitations
While k6 thresholds provide a clear pass/fail signal, they have some constraints:
- Evaluation granularity – thresholds are calculated per aggregation window. Very short windows can make the test sensitive to transient spikes, while long windows may hide short‑lived violations.
- Single‑metric focus – k6 thresholds evaluate each metric independently. Correlated failures (e.g., latency spikes causing higher error rates) are not automatically detected unless you create a combined expression.
- No impact on the system under test – the thresholds only affect the test outcome; they do not enforce runtime limits on the service itself.
To mitigate these issues, choose an aggregation period that matches your traffic pattern (e.g., 5 seconds for bursty workloads) and consider adding a custom metric that captures error‑rate spikes to trigger a separate threshold.
Actionable closing
To embed SLA validation into your development workflow:
- Write a k6 script that exercises the critical API paths under realistic load.
- Define thresholds that reflect your SLA (latency p(95) and error rate). Use expressions like
p(95)<200for latency andrate<0.001for errors. - Run the script locally with
--out jsonto generate a report, verify the exit status, and inspect the threshold values. - Add the command to your CI pipeline (e.g., GitHub Actions, GitLab CI). Fail the job if the exit code is non‑zero, and optionally publish the JSON report as an artifact for later analysis.
- Periodically review the reports. If thresholds are frequently breached, adjust the SLA or investigate performance bottlenecks.
By treating thresholds as a first‑class part of your performance tests, you turn SLA compliance from a manual audit into an automated gate that protects both users and your release pipeline.