Load testing a web API with k6

By

Updated

Tagged: DevTools

Learn load testing with k6 by testing a web API under smoke, average, and spike traffic, adding checks, thresholds, scenarios, and CI.

A response can be fast when one person uses an API and slow when five hundred people use it.

Functional tests answer:

Does this endpoint return the right result?

A load test answers:

Does it still return the right result, quickly enough, under expected traffic?

In this tutorial we’ll use k6 to test a small HTTP API.

We’ll write:

Then we’ll run the smoke test in CI.

Install k6

On macOS:

brew install k6

For other platforms, grab the right package from the official k6 installation docs.

Check that it’s installed:

k6 version

You write k6 tests in JavaScript or TypeScript, but k6 isn’t Node.js. It runs on its own runtime with its own modules, so don’t expect every npm package or Node built-in module to work inside a k6 script.

Choose a safe test target

Never load test a service you don’t own or don’t have permission to test.

Start locally or in an isolated staging environment. A load test can create real traffic, data, emails, charges, and alerts.

Let’s assume our API exposes these endpoints:

GET  http://localhost:3000/health
GET  http://localhost:3000/books
GET http://localhost:3000/books/1
POST http://localhost:3000/test-session

GET /books/1 returns:

{
  "id": "1",
  "title": "The Hobbit"
}

GET /books returns:

{
  "books": [
    {
      "id": "1",
      "title": "The Hobbit"
    }
  ]
}

POST /test-session creates a short-lived test credential:

{
  "token": "test-token"
}

The health endpoint returns 200 when the API is ready.

Write the first test

Create tests/load/smoke.js:

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

export const options = {
  vus: 1,
  duration: '10s',
}

export default function () {
  const response = http.get('http://localhost:3000/books/1')
  let hasTitle = false

  try {
    hasTitle = typeof response.json('title') === 'string'
  } catch {
    hasTitle = false
  }

  check(response, {
    'status is 200': (result) => result.status === 200,
    'body contains a title': () => hasTitle,
  })

  sleep(1)
}

Run it:

k6 run tests/load/smoke.js

A virtual user, or VU, runs the default function over and over.

Here, our single VU:

  1. sends a request
  2. checks the response
  3. waits one second
  4. repeats for ten seconds

That’s a smoke test. It verifies that the script and target environment work under almost no load.

Checks do not fail the test by themselves

check() records whether an assertion passed, but a failed check doesn’t make the k6 process exit with an error on its own.

To fail the test when a check fails, add a threshold:

export const options = {
  vus: 1,
  duration: '10s',
  thresholds: {
    checks: ['rate==1'],
  },
}

Now all checks have to pass, because thresholds turn those expectations into pass or fail conditions.

Add performance thresholds

Say your API requirements are:

You can write them directly as thresholds:

export const options = {
  vus: 1,
  duration: '10s',
  thresholds: {
    checks: ['rate==1'],
    http_req_failed: ['rate<0.01'],
    http_req_duration: ['p(95)<300', 'p(99)<800'],
  },
}

p(95) is the 95th percentile, meaning 95% of measured request durations finished below that value.

Averages can hide a bad experience. Nine fast requests and one very slow request can still produce a decent average, while percentiles show that slow tail right away.

Use an environment variable for the URL

Hardcoding localhost makes the script hard to reuse, so read the target URL from an environment variable instead:

const baseUrl = __ENV.BASE_URL || 'http://localhost:3000'

export default function () {
  const response = http.get(`${baseUrl}/books/1`)
  // ...
}

Now you can run the same script against staging:

k6 run \
  -e BASE_URL=https://staging.example.com \
  tests/load/smoke.js

Keep credentials out of the script and repository too. Pass them through environment variables or your CI secret system.

Understand the test lifecycle

A k6 test runs in four phases:

  1. init code runs once per VU (and may run more often in cloud execution)
  2. setup() runs once for the whole test
  3. the default function runs repeatedly for each VU
  4. teardown() runs once at the end

Use setup() for shared preparation before the VUs start:

export function setup() {
  const response = http.post(
    `${baseUrl}/test-session`,
    JSON.stringify({
      role: 'load-tester',
    }),
    {
      headers: {
        'content-type': 'application/json',
      },
    }
  )

  if (response.status !== 200) {
    throw new Error(`Test session failed with ${response.status}`)
  }

  let token

  try {
    token = response.json('token')
  } catch {
    throw new Error('Test session did not return JSON')
  }

  if (typeof token !== 'string' || token.length === 0) {
    throw new Error('Test session did not return a token')
  }

  return {
    token,
  }
}

export default function (data) {
  http.get(`${baseUrl}/books/1`, {
    headers: {
      authorization: `Bearer ${data.token}`,
    },
  })
}

Don’t put an expensive login inside every iteration unless login itself is what you want to load test.

Just watch out for sharing one account across all VUs, since that can create unrealistic locking or cache behavior. For a serious test, prepare a pool of representative test users.

Test average traffic with scenarios

vus and duration work fine for a first test, while scenarios let you control how traffic changes over time.

Create tests/load/average.js:

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

const baseUrl = __ENV.BASE_URL || 'http://localhost:3000'

export const options = {
  scenarios: {
    average_load: {
      executor: 'ramping-vus',
      startVUs: 0,
      stages: [
        { duration: '30s', target: 20 },
        { duration: '2m', target: 20 },
        { duration: '30s', target: 0 },
      ],
      gracefulRampDown: '10s',
    },
  },
  thresholds: {
    checks: ['rate>0.99'],
    http_req_failed: ['rate<0.01'],
    http_req_duration: ['p(95)<300'],
  },
}

export default function () {
  const response = http.get(`${baseUrl}/books/1`, {
    tags: {
      name: 'GET /books/:id',
    },
  })

  check(response, {
    'status is 200': (result) => result.status === 200,
  })

  sleep(Math.random() * 2 + 1)
}

This test ramps up to 20 concurrent virtual users, holds there for two minutes, then ramps back down.

Adding a random sleep keeps every VU from hitting the server in lockstep.

Closed and open workload models

The ramping-vus executor uses a closed model: each VU waits for its request to finish before starting the next iteration. If the server slows down, the request rate drops with it.

That makes sense for a small group of users, but it can hide overload on a public endpoint where new requests keep arriving whether the previous ones finished or not.

An open model starts iterations at a configured rate instead:

export const options = {
  scenarios: {
    api_traffic: {
      executor: 'ramping-arrival-rate',
      startRate: 10,
      timeUnit: '1s',
      preAllocatedVUs: 20,
      maxVUs: 100,
      stages: [
        { duration: '1m', target: 50 },
        { duration: '3m', target: 50 },
        { duration: '1m', target: 0 },
      ],
    },
  },
}

This targets a steady number of iterations per second even when responses slow down, up to the available VUs. Pick whichever workload model matches how traffic reaches your real system.

Create a spike test

A spike test checks what happens when traffic jumps suddenly.

Create tests/load/spike.js:

import http from 'k6/http'
import { sleep } from 'k6'

const baseUrl = __ENV.BASE_URL || 'http://localhost:3000'

export const options = {
  scenarios: {
    spike: {
      executor: 'ramping-vus',
      startVUs: 5,
      stages: [
        { duration: '30s', target: 5 },
        { duration: '10s', target: 100 },
        { duration: '1m', target: 100 },
        { duration: '10s', target: 5 },
        { duration: '30s', target: 5 },
      ],
    },
  },
  thresholds: {
    http_req_failed: ['rate<0.05'],
    http_req_duration: ['p(95)<1000'],
  },
}

export default function () {
  http.get(`${baseUrl}/books/1`)
  sleep(1)
}

The thresholds here are looser than in the average-load test. You’ll have to decide with your team how much slowdown or error rate is acceptable during a traffic spike.

After the spike drops off, check whether the service recovers. If it stays slow once traffic returns to normal, you may have exhausted a connection pool, filled a queue, or triggered expensive retries.

Group requests by route, not raw URL

If every book ID gets tracked as its own URL metric, your results end up with too many time series.

Tag dynamic routes with a stable name instead:

http.get(`${baseUrl}/books/${bookId}`, {
  tags: {
    name: 'GET /books/:id',
  },
})

Then attach a threshold to that route:

thresholds: {
  'http_req_duration{name:GET /books/:id}': ['p(95)<300'],
}

It’s the same cardinality problem you run into with production metrics, so stick to bounded labels.

Test a realistic flow

A single endpoint hit rarely represents a real person. A basic browsing flow might list books first and then open one of them:

export default function () {
  const list = http.get(`${baseUrl}/books`)

  check(list, {
    'list loaded': (result) => result.status === 200,
  })

  sleep(2)

  const book = http.get(`${baseUrl}/books/1`)

  check(book, {
    'book loaded': (result) => result.status === 200,
  })

  sleep(3)
}

Keep your test data isolated. If you’re running a write-heavy test, clean up after it finishes or use data you can throw away with the entire test environment.

Read the results

k6 prints a lot of built-in metrics. Start with these:

Look at those numbers alongside your server metrics:

The k6 output shows when latency jumped or errors started climbing, and your server telemetry is where you’ll find the bottleneck behind it.

Run the smoke test in CI

Don’t run a large load test on every pull request. It’s slow, noisy, and can conflict with other builds.

A short smoke test works well in CI, though. Assuming your workflow already started the API:

- name: Run API
  run: npm start &

- name: Wait for API
  run: npx --yes wait-on@9.1.0 http-get://localhost:3000/health

- name: Run k6 smoke test
  run: |
    docker run --rm --network host \
      -v "$PWD:/work" \
      -w /work \
      grafana/k6 run tests/load/smoke.js

Networking varies between CI systems and Docker environments. If --network host isn’t available, run k6 as an installed binary or put both services on the same Docker network.

Save longer tests for a scheduled run against an isolated environment, or run them before a major release.

Avoid misleading tests

It’s easy to get misleading numbers from a load test if the setup is off. Watch out for these mistakes:

Get a repeatable baseline first, then change one thing at a time and compare the results.

A practical testing sequence

Split your load testing into small, focused tests:

  1. smoke: does the script work?
  2. average load: does expected traffic meet the service objectives?
  3. stress: where does performance begin to degrade?
  4. spike: does the system survive a sudden jump?
  5. soak: does it remain healthy for hours?

You don’t need all five on day one. Start with expected traffic and explicit thresholds tied to what your API needs to hit, so you can tell right away whether a run passed or failed.

Want me to talk about your product? You can sponsor this site.

Related posts about devtool: