Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Lab · 30 min · revision 4

Lab: A Reproducible Load Test

Seed a small catalog service with fixed data, state a falsifiable performance goal, and run an open-model k6 test with a warm-up scenario and thresholds that report p50, p95, p99 and error rate for the steady state only.

Contentsand lesson path

What you will learn

  • State a performance goal in latency percentiles and throughput, and run a reproducible load test that reports p50, p95, p99 and error rate.

01. Goal and setup

A load test is useful only if it can fail. "The catalog should be fast" cannot fail, so it tells you nothing. A falsifiable performance goal names three things: the latency percentiles that must hold, the request rate at which they must hold, and the highest error rate you accept. A latency target without a rate can be met by sending very little traffic, and a target without an error ceiling can be met by a service that fails quickly.

In this lab you build a small catalog service with a fixed, seeded dataset, then test it against this goal: at a steady 100 requests per second, GET /api/v1/catalog keeps p50 under 50 ms, p95 under 150 ms and p99 under 300 ms, with fewer than 0.1% failed requests. The numbers are a budget you choose for the product, not something you read off the first run.

You need: Python 3.12 or later, k6 v1.0 or later (tested with v2.4.0), and a terminal. Tested package versions: FastAPI 0.163.1 and Uvicorn 0.54.0.

Here k6 and the service run on one machine and talk over the loopback interface (127.0.0.1). That is fine for learning the method and for comparing two versions of your own code on the same machine. It is not a capacity measurement: loopback has no real network, and the two processes compete for the same CPU. That is why the script reads its target from BASE_URL, so the same test can later run from a separate machine against a staging host.

Project layout at the end of the lab
loadlab/
├── seed.py                step 1: builds catalog.db with fixed data
├── app.py                 step 2: the catalog service
└── catalog-load-test.js   step 3: the k6 test

02. Step 1: Install the tools and seed the data

The seed script writes 200,000 products in 50 categories to a SQLite file. It uses random.Random(42), a random generator with a fixed seed, so every run on every machine produces exactly the same rows. The last line prints a count and a sum: if yours match the expected output, you are testing the same data as everyone else. The index on (category_id, price_cents) serves the endpoint's query: filter by category, sort by price.

Terminal
mkdir loadlab && cd loadlab
python3 -m venv .venv && source .venv/bin/activate
pip install "fastapi==0.163.1" "uvicorn==0.54.0"
Python · seed.py
"""Create catalog.db: 200,000 products in 50 categories, the same on every run."""
import random
import sqlite3
from pathlib import Path

DB = Path("catalog.db")
DB.unlink(missing_ok=True)
rng = random.Random(42)  # fixed seed: same rows on every machine
rows = [
    (i, f"product-{i:06d}", rng.randint(1, 50), rng.randint(199, 99_999))
    for i in range(1, 200_001)
]
con = sqlite3.connect(DB)
con.execute(
    "CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT NOT NULL,"
    " category_id INTEGER NOT NULL, price_cents INTEGER NOT NULL)"
)
con.executemany("INSERT INTO products VALUES (?, ?, ?, ?)", rows)
con.execute(
    "CREATE INDEX idx_products_cat_price ON products (category_id, price_cents)"
)
con.commit()
count, total = con.execute("SELECT count(*), sum(price_cents) FROM products").fetchone()
print(f"products={count} sum_price_cents={total}")
con.close()
Terminal
python seed.py
Expected output
products=200000 sum_price_cents=10023523911

03. Step 2: Start the service and check one request

The service has one read endpoint and a health check. FastAPI runs plain def routes in a thread pool, so each worker thread keeps its own SQLite connection instead of opening a new one per request. The connection is read-only and marked immutable=1, which tells SQLite that the file cannot change while the service runs, so it can skip file locking on every query. That is safe here only because nothing writes to catalog.db during the test; SQLite's documentation warns that it may return wrong results if an immutable file changes.

Python · app.py
"""Catalog service for the load-test lab: one read endpoint and a health check."""
import sqlite3
import threading

from fastapi import FastAPI, Query

app = FastAPI()
local = threading.local()  # one connection per worker thread, reused


def db() -> sqlite3.Connection:
    if not hasattr(local, "con"):
        # Read-only, and immutable: the seeded file does not change during
        # the test, so SQLite can skip file locking on every query
        uri = "file:catalog.db?mode=ro&immutable=1"
        local.con = sqlite3.connect(uri, uri=True)
    return local.con


@app.get("/healthz")
def healthz() -> dict:
    return {"status": "ok"}


@app.get("/api/v1/catalog")
def catalog(
    category: int = Query(ge=1, le=50), limit: int = Query(20, ge=1, le=50)
):
    rows = db().execute(
        "SELECT id, name, price_cents FROM products WHERE category_id = ?"
        " ORDER BY price_cents LIMIT ?",
        (category, limit),
    ).fetchall()
    items = [{"id": r[0], "name": r[1], "price_cents": r[2]} for r in rows]
    return {"category": category, "count": len(items), "items": items}
Terminal 1 · leave it running
uvicorn app:app --host 127.0.0.1 --port 8000 --no-access-log
Terminal 2
URL=http://127.0.0.1:8000/api/v1/catalog
curl -s "$URL?category=7&limit=1" | python3 -m json.tool
curl -s -o /dev/null -w "%{http_code}\n" "$URL?category=99"
Expected output
{
    "category": 7,
    "count": 1,
    "items": [
        {
            "id": 144487,
            "name": "product-144487",
            "price_cents": 200
        }
    ]
}
422

The first line is the cheapest product in category 7, the same on every machine because the data is seeded. The 422 shows that an out-of-range category is rejected by validation; limit is bounded the same way, because SQLite reads a negative LIMIT as no limit at all. A load test that sent invalid requests would measure error handling, not the catalog.

04. Why the test uses an open model

Many load scripts use a closed model: a fixed number of virtual users (VUs), each sending a request, waiting for the reply and sending the next. When the server stalls for three seconds, say on a lock wait, every VU is stuck waiting, so almost no new requests are sent during the stall. The generator eases off exactly when the server struggles. Each stuck request is recorded once as slow, but the hundreds of requests that real users would have sent during those three seconds, and that would all have queued, are never sent and never measured. This bias is called coordinated omission, and it makes p95 and p99 look better than what users see.

An open model schedules arrivals on a clock instead: 100 requests per second means a new request every 10 ms, whether or not earlier ones have finished. In k6 the constant-arrival-rate executor does this. It still needs a free VU to start each request; if all maxVUs are busy, k6 skips the request and counts it in dropped_iterations. A run with dropped iterations did not keep the schedule, so the test treats any dropped iteration as a failure.

05. Step 3: Write the load test with a warm-up

The first seconds of a run are unlike the rest: connections are opened, worker threads start, caches are empty. If those samples count, you measure start-up, not the steady state your goal is about. The script therefore has two scenarios. warmup sends 20 requests per second for 10 seconds; steady starts at startTime: "10s", when the warm-up ends, and sends 100 per second for 30 seconds.

k6 tags every sample with the name of the scenario that produced it. Writing a threshold as http_req_duration{scenario:steady} makes it a check on that subset only, so warm-up samples cannot pass or fail the goal. summaryTrendStats adds p(50) and p(99) to the summary; the default list stops at p(95). The thresholds are your goal from the setup section, written as code. Keep the run short, as here, while you develop; real steady-state runs usually last several minutes.

JavaScript · catalog-load-test.js
import http from "k6/http";
import { check } from "k6";
import exec from "k6/execution";

// Target comes from the environment, so the same script can hit staging later
const BASE_URL = __ENV.BASE_URL || "http://127.0.0.1:8000";

export const options = {
  scenarios: {
    warmup: {
      // Light traffic first: opens connections and fills caches
      executor: "constant-arrival-rate",
      rate: 20, timeUnit: "1s", duration: "10s",
      preAllocatedVUs: 20, maxVUs: 50,
    },
    steady: {
      // Open model: 100 new requests every second, whatever the latency
      executor: "constant-arrival-rate",
      rate: 100, timeUnit: "1s", duration: "30s",
      startTime: "10s", // begins when the warm-up ends
      preAllocatedVUs: 50, maxVUs: 100,
    },
  },
  summaryTrendStats: ["avg", "p(50)", "p(95)", "p(99)", "max"],
  thresholds: {
    // {scenario:steady}: only steady-state samples count towards the goal
    "http_req_duration{scenario:steady}": ["p(50)<50", "p(95)<150", "p(99)<300"],
    "http_req_failed{scenario:steady}": ["rate<0.001"],
    "dropped_iterations{scenario:steady}": ["count==0"],
  },
};

export default function () {
  // Spread requests over all 50 categories in a fixed order
  const category = (exec.scenario.iterationInTest % 50) + 1;
  const res = http.get(`${BASE_URL}/api/v1/catalog?category=${category}`);
  check(res, { "status is 200": (r) => r.status === 200 });
}

06. Step 4: Run it and read the summary

Terminal 2 · about 40 seconds
BASE_URL=http://127.0.0.1:8000 k6 run --quiet catalog-load-test.js
Illustrative output (trimmed; from a real run, your timings will differ)
  █ THRESHOLDS

    dropped_iterations{scenario:steady}
    ✓ 'count==0' count=0

    http_req_duration{scenario:steady}
    ✓ 'p(50)<50' p(50)=1.53ms
    ✓ 'p(95)<150' p(95)=2.46ms
    ✓ 'p(99)<300' p(99)=4.87ms

    http_req_failed{scenario:steady}
    ✓ 'rate<0.001' rate=0.00%

  █ TOTAL RESULTS

    HTTP
    http_req_duration...........: avg=1.68ms p(50)=1.53ms p(95)=2.44ms p(99)=4.84ms
      { scenario:steady }.......: avg=1.69ms p(50)=1.53ms p(95)=2.46ms p(99)=4.87ms
    http_req_failed.............: 0.00%  0 out of 3201
      { scenario:steady }.......: 0.00%  0 out of 3000
    http_reqs...................: 3201   80.020963/s

Read the summary in this order. First dropped_iterations: zero means k6 kept the 100 requests per second schedule. Then the error rate, and only then the percentiles. THRESHOLDS shows steady-state values only. Under TOTAL RESULTS, the plain http_req_duration line includes the warm-up, and the { scenario:steady } line below it is the subset your goal is judged on: about 3,000 requests, 100 per second for 30 seconds. In another run on the same machine, the total max was 273 ms while the steady-state max was 29 ms; the warm-up alone produced the slow outliers.

Now write the result as a statement someone else can check: "at 100 req/s steady, p50 1.5 ms, p95 2.5 ms, p99 4.9 ms, 0 errors in 3,000 requests, seeded data sum_price_cents=10023523911, k6 and service on one machine". Because the data, script and rate are fixed, a colleague can rerun it, and a later code change can be compared with it.

07. Step 5: Prove that the gate can fail

A gate that never fails is not a gate. Point the test at a port where nothing listens. --log-output=none hides the thousands of "connection refused" warnings.

Terminal 2
BASE_URL=http://127.0.0.1:8001 k6 run --quiet --log-output=none catalog-load-test.js
echo "exit code: $?"
Illustrative output (trimmed; from a real run)
    http_req_duration{scenario:steady}
    ✓ 'p(50)<50' p(50)=0s
    ✓ 'p(95)<150' p(95)=0s
    ✓ 'p(99)<300' p(99)=0s

    http_req_failed{scenario:steady}
    ✗ 'rate<0.001' rate=100.00%
...
exit code: 99

Every request failed, yet all three latency thresholds passed: a request that is refused at once takes almost no time. Only the error ceiling caught the problem, which is why a goal without one is incomplete. k6 exits with code 99 when any threshold fails, so a CI job that runs this script stops the pipeline without extra tooling.

08. Check your understanding

Practice check · 3 questions

Reading a load test run

Three questions about reading the k6 output from this lab.

Q1. A k6 run with the constant-arrival-rate executor reports dropped_iterations = 4,200. What does that tell you?
Q2. In one run, the plain http_req_duration line shows max=273ms, while the { scenario:steady } line shows max=29ms and every threshold passes. What explains the difference?
Q3. The service was down for a whole run. The latency thresholds show p(95)=0s and pass. What should you conclude?
Practice only: not graded, not saved, not evidence.

09. Apply it

Turn this lab into the first part of the skill project: load-testing the three busiest endpoints of your own service.

  • Write the goal for each endpoint first: percentiles, request rate and error ceiling, taken from what your users need.
  • Seed a staging database with a fixed script, as in step 1, and record a checksum with every result so that runs on different data are never compared.
  • Run k6 from a machine other than the service, with BASE_URL pointing at staging, so loopback and CPU sharing do not flatter the numbers.
  • Keep the warm-up scenario and the scoped thresholds, and add the script to CI so that exit code 99 blocks a release that breaks the goal.
  • As an experiment, drop the index in catalog.db, rerun step 4, and see which threshold fails first.

The skill project suggests Locust; the same method applies there: fixed data, a target from an environment variable, a warm-up you exclude, and percentiles judged at a fixed rate. The next lesson shows how to profile an endpoint that failed its goal.

10. Review prompt

Without looking back, write a falsifiable goal for an endpoint you know. Explain why a closed-loop generator understates tail latency, what dropped_iterations tells you about an open-model run, why the thresholds in this lab are scoped to the steady scenario, and why a run where every request fails can still pass its latency thresholds.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check