How-To Guide

How to Load Test an API with k6

Measure how an API behaves under realistic load with scripted virtual users, thresholds and staged ramps before real traffic arrives.

On this page

  1. Introduction
  2. What to Measure and Why
  3. Scripting a Realistic Scenario
  4. Ramping the Load
  5. Thresholds as Pass or Fail
  6. Interpreting the Results
  7. Operational Discipline
  8. Conclusion

Introduction

An API that is fast for one request is not necessarily fast for a thousand concurrent ones, and the difference is invisible until a launch or an incident exposes it. Load testing measures that difference deliberately. A good load test models real traffic: a mix of endpoints, think time between calls, a ramp rather than an instant jump, and thresholds that define pass or fail by the metrics that matter. k6 runs these tests as scripts, so the load profile is code you can review and repeat. This article covers scripting a realistic scenario, ramping the load, setting thresholds, and interpreting the results.

What to Measure and Why

Throughput, or requests per second, is a vanity metric on its own; latency at that throughput is what users feel. Report percentile latencies, especially p95 and p99, because the average hides the tail that makes users complain. Error rate under load matters too, because a system that returns errors quickly looks fast by latency and is failing by every other measure.

Capacity is the load at which latency or errors cross an unacceptable line. A load test’s job is to find that line and to show how the system behaves as it approaches it: does latency rise gradually, indicating a queue, or cliff sharply, indicating a saturation point? The shape tells you what to fix.

Scripting a Realistic Scenario

A test that hammers one endpoint is easy but misleading. Model the mix: most users browse, some act, a few do the expensive operation. Include think time between requests so the virtual users resemble humans rather than a tight loop, and vary the parameters so caches behave as they would in production rather than all hitting one key.

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

export const options = {
  scenarios: {
    browsing: {
      executor: 'ramping-vus',
      startVUs: 0,
      stages: [
        { duration: '2m', target: 50 },   // ramp up
        { duration: '5m', target: 50 },   // steady state
        { duration: '2m', target: 0 },    // ramp down
      ],
    },
  },
  thresholds: {
    http_req_duration: ['p(95)<300', 'p(99)<800'],  // fail if tail is slow
    http_req_failed: ['rate<0.01'],                  // fail if >1% errors
  },
};

export default function () {
  const list = http.get('http://localhost:8080/products?limit=20');
  check(list, { 'list 200': (r) => r.status === 200 });
  sleep(Math.random() * 2);                 // think time between calls
  const id = list.json('items')[0].id;
  const detail = http.get('http://localhost:8080/products/' + id);
  check(detail, { 'detail 200': (r) => r.status === 200 });
  sleep(1);
}

Ramping the Load

Starting at full load hides the ramp behaviour and can overwhelm a cold system for the wrong reason. Ramp in stages so you see how latency changes as concurrency grows, and so connection pools and caches warm. A steady-state phase long enough to reach a stable measurement is the part you compare between runs.

Run the test against an environment that resembles production in the ways that matter: the same instance size, the same database, the same cache, the same upstream mocks or stubs. A load test against a laptop-backed development server tells you about the laptop. If you must test a scaled-down environment, scale the results explicitly and state the assumptions.

Thresholds as Pass or Fail

Thresholds turn a load test into a gate. Define them in the metrics users feel: p95 and p99 latency, error rate, and any business assertion such as “checkout completes”. A run that breaches a threshold exits nonzero, so it can fail CI. Without a threshold, a load test produces numbers that people interpret differently and ignore.

Set thresholds from an SLO rather than from the last run, or you will ratchet the bar to whatever you currently achieve. Tie the p95 threshold to the latency the product promises and the error threshold to the error budget. Then a regression shows up as a red test rather than a discussion.

Interpreting the Results

Read the latency distribution and the trend over time, not just the summary. A p99 that grows linearly with virtual users points to a queuing resource such as a connection pool; a cliff points to a hard limit such as file descriptors. Correlate the load test with server-side metrics: CPU, memory, connection-pool usage and queue depth show which resource saturated first.

Look for the knee: the point where adding load stops adding throughput and starts adding latency. That is your practical capacity. Running past the knee without understanding it only generates errors. The goal is to locate the knee and know the margin you have, not to push until something breaks.

# Run the scripted profile and export both a summary and time-series data
k6 run --out json=results.json --summary-export=summary.json load-test.js

# The text summary shows percentiles; failing thresholds exit non-zero:
#   http_req_duration........: avg=85ms med=72ms p(95)=210ms p(99)=640ms
#   http_req_failed..........: 0.0042%  ✓ rate<0.01
#   ✓ p(95)<300   ✓ p(99)<800
# A breached threshold aborts with:
#   ERRO[0000] thresholds on metrics 'http_req_duration' have been crossed

Operational Discipline

Never load test production unless you have explicit permission and a kill switch. A load test is a denial-of-service tool if pointed at a system you do not own, and even on your own system it can affect real users. Run in a dedicated environment or behind a feature flag that isolates the traffic.

Run the same test after every significant change so you can see a regression, and keep the scripts in the repository next to the code. A load test that is run once during a launch and then forgotten will be out of date the next time you need it. Repeatability, achieved by scripting the profile, is what makes the numbers comparable across time.

Conclusion

Load testing with scripted virtual users replaces guesswork about capacity with measured percentile latency, error rate and the shape of the curve. Model a realistic endpoint mix with think time, ramp the load in stages, define pass or fail thresholds from your SLO, and find the knee where throughput stops growing. Read the distribution alongside server-side saturation metrics, run in an environment that resembles production, and keep the scripts versioned so regressions are visible. Then capacity becomes a number you know rather than a surprise you meet.

Sources: k6 documentation, k6 thresholds, k6 scenarios.

FAQ

Why report p95 and p99 instead of average latency?
The average hides the tail that users actually complain about. A system can have a comfortable average while one in a hundred requests is unacceptably slow. Percentiles expose that tail, and the tail is what determines whether the service feels fast.
Is it safe to load test production?
Only with explicit permission and a kill switch, and ideally not at all. A load test can degrade service for real users and, if pointed at a system you do not own, is essentially a denial-of-service attack. Prefer an environment that resembles production.

Related Examples