Reliability and CI

Add a k6 smoke test

Send a small controlled workload to the Books API and define thresholds that turn latency and error expectations into pass or fail.

8 minute lesson

~~~

Load testing asks how the system behaves under traffic. Begin with a tiny smoke run against infrastructure you own.

A k6 script describes virtual users, duration, requests, checks, and thresholds. Protect shared systems: start small, use test data, coordinate larger runs, and stop if error rate or resource pressure becomes unsafe.

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

export const options = {
  vus: 2,
  duration: '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('http://localhost:3000/books')
  check(response, { 'status is 200': r => r.status === 200 })
}

A check records whether each response has the expected content. It does not, by itself, make k6 exit with a failed status. A threshold is the pass/fail contract for the run, so the checks threshold connects failed checks to CI. The other thresholds say that fewer than 1% of HTTP requests may fail and that 95% must complete within 300 milliseconds.

The percentile matters. Averages can hide a slow tail: nine fast requests and one very slow request may still produce an acceptable average while a real user experiences the outlier. Choose values from an actual service expectation or measured baseline, not from a number that merely makes today’s run green.

A smoke test asks whether the system survives a tiny controlled workload and produces valid responses. It is not a capacity claim. Two virtual users for ten seconds cannot tell you the maximum throughput. Larger tests need representative traffic, isolated test data, observability, and coordination with whoever owns the environment.

Run against infrastructure you own and start locally or in a dedicated environment. A fast 200 error page is still wrong, so check both status and a small stable body property. Avoid including credentials or unbounded test-data creation in the script.

Run the smoke test locally and record request count, p95 latency, error rate, and check rate. Break the response body while keeping status 200, then make the route slow. Confirm that the two changes fail different thresholds.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →