Testing and QA · Intermediate · 22 min
Load test a web app with Locust in Python
By Padding · Updated 18 Nov 2026
Debian (python:3.15-slim) · Python 3.15 · Locust 2.47.0 · uv 0.13
You will write a Locust 2.47 test in Python that signs in, browses, searches and adds to a cart on a small local shop app, then run it headless with a CSV report and an exit code that fails the run when errors or p95 latency cross your limits.
On this page
A load test answers one question before your users do: what happens to this app when many people use it at once? Locust is a load testing tool where the users are Python classes. Each simulated user runs your code in a loop: sign in once, then pick an action, wait a little, pick another. Because the behaviour is plain Python, it can branch on what the server answered, keep state per user and reuse your own helper modules.
That is the main reason to pick Locust over k6. Choose Locust when your team writes Python, when a user journey needs real logic (read a basket ID from one answer, decide the next step from it), or when you want to reuse Python libraries for test data. Choose k6 when your team prefers JavaScript, when you want thresholds and scenarios built into the tool, or when you need very high request rates from one small machine. Both are fine for the size of test in this tutorial.
You will test a small shop API that you write yourself and run on 127.0.0.1. Only load test systems you own or have written permission to test: a load test against someone else's server looks the same as an attack.
Step 1 · Create the project and install Locust
Make a throwaway project and add Locust. The version range allows patch releases of 2.47 and nothing newer, so an upgrade cannot change behaviour under you between runs:
mkdir -p ~/locust-demo
cd ~/locust-demo
uv init --no-package
uv add "locust>=2.47,<2.48"
rm main.pyLocust pulls in gevent, which runs thousands of simulated users as lightweight green threads inside one process, plus Flask for its web interface. On Linux they install from prebuilt wheels for Python 3.15, so nothing is compiled.
Check it worked
uv run locust --versionThe output starts with locust 2.47.0, followed by the install path and Python version.
Step 2 · Write a small shop app to test
Create shop.py. It is the system under test: a standard-library HTTP server with five routes. Sign-in returns a token, product routes are open, and the cart needs the token. Two details matter later. Product pages wait 20 to 80 ms, like a real database lookup. And every tenth search returns status 200 with an error in the body, a bug that a plain status-code check misses.
The password comes from the SHOP_PASSWORD environment variable, so no secret is written into the code:
cat > shop.py <<'PY'
import json
import os
import random
import secrets
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse
PASSWORD = os.environ.get("SHOP_PASSWORD")
if not PASSWORD:
raise SystemExit("Set SHOP_PASSWORD before starting the shop.")
PRODUCTS = [
{"id": n, "name": f"{kind} {n}", "price": 500 + n * 25}
for n, kind in enumerate(["lamp", "mug", "phone case", "bag"] * 5, start=1)
]
TOKENS = set()
lock = threading.Lock()
searches = 0
class Handler(BaseHTTPRequestHandler):
def send_json(self, status, payload):
body = json.dumps(payload).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def read_json(self):
length = int(self.headers.get("Content-Length", 0))
try:
return json.loads(self.rfile.read(length) or b"{}")
except ValueError:
return {}
def do_GET(self):
global searches
url = urlparse(self.path)
if url.path == "/api/products":
return self.send_json(200, PRODUCTS)
if url.path.startswith("/api/products/"):
time.sleep(random.uniform(0.02, 0.08))
wanted = url.path.rsplit("/", 1)[1]
for product in PRODUCTS:
if str(product["id"]) == wanted:
return self.send_json(200, product)
return self.send_json(404, {"error": "no such product"})
if url.path == "/api/search":
term = parse_qs(url.query).get("q", [""])[0]
with lock:
searches += 1
broken = searches % 10 == 0
if broken:
return self.send_json(200, {"error": "search index busy", "results": []})
found = [p for p in PRODUCTS if term in p["name"]]
return self.send_json(200, {"results": found})
self.send_json(404, {"error": "not found"})
def do_POST(self):
data = self.read_json()
if self.path == "/api/login":
if data.get("username") == "shopper" and data.get("password") == PASSWORD:
token = secrets.token_hex(16)
with lock:
TOKENS.add(token)
return self.send_json(200, {"token": token})
return self.send_json(401, {"error": "wrong username or password"})
if self.path == "/api/cart":
token = self.headers.get("Authorization", "").removeprefix("Bearer ")
if token not in TOKENS:
return self.send_json(401, {"error": "sign in first"})
return self.send_json(201, {"added": data.get("product_id")})
self.send_json(404, {"error": "not found"})
def log_message(self, format, *args):
pass
ThreadingHTTPServer(("127.0.0.1", 8000), Handler).serve_forever()
PYIn your second terminal, go to the same folder, set a practice password at the prompt (it is not echoed and stays out of your shell history), and start the shop. Leave it running:
cd ~/locust-demo
read -rs -p "Practice password: " SHOP_PASSWORD; echo
export SHOP_PASSWORD
uv run shop.pyBack in your first terminal, set the same password the same way, so Locust can sign in:
read -rs -p "Practice password: " SHOP_PASSWORD; echo
export SHOP_PASSWORDCheck it worked
python3 -c "import json, urllib.request; print(len(json.load(urllib.request.urlopen('http://127.0.0.1:8000/api/products'))), 'products')"The output is 20 products. If you see Connection refused, the shop is not running in the second terminal.
Step 3 · Describe a shopper as a Locust user
Create locustfile.py. A class that extends HttpUser is one kind of visitor. Locust creates as many instances as you ask for, and each one gets its own HTTP session, so cookies and headers set by one simulated user do not leak into another:
cat > locustfile.py <<'PY'
import os
import random
from locust import HttpUser, between, task
PASSWORD = os.environ.get("SHOP_PASSWORD")
if not PASSWORD:
raise SystemExit("Set SHOP_PASSWORD before running Locust.")
PRODUCT_IDS = list(range(1, 21))
SEARCH_TERMS = ["lamp", "mug", "phone", "bag"]
class Shopper(HttpUser):
wait_time = between(1, 3)
def on_start(self):
response = self.client.post(
"/api/login", json={"username": "shopper", "password": PASSWORD}
)
token = response.json().get("token", "")
self.client.headers["Authorization"] = f"Bearer {token}"
@task(6)
def browse(self):
self.client.get("/api/products")
@task(3)
def view_product(self):
product_id = random.choice(PRODUCT_IDS)
self.client.get(f"/api/products/{product_id}", name="/api/products/[id]")
@task(2)
def search(self):
term = random.choice(SEARCH_TERMS)
self.client.get("/api/search", params={"q": term}, name="/api/search")
@task(1)
def add_to_cart(self):
product_id = random.choice(PRODUCT_IDS)
self.client.post("/api/cart", json={"product_id": product_id, "quantity": 1})
PYWhat each part does:
wait_time = between(1, 3)makes each user pause for a random 1 to 3 seconds after every task. This is think time. Without it, each user fires requests as fast as the server answers, which tells you about raw capacity but not about how many people the app can serve.on_startruns once per user before its first task. Signing in here means every user has a token, and the sign-in route is hit once per user, as it is in real life.@task(6),@task(3)and so on are weights. Out of every 12 picks, a user browses about 6 times, views a product about 3 times, searches about twice and adds to the cart about once. Set the weights from your analytics if you have them.name="/api/products/[id]"groups twenty different URLs into one row of results. Without it, each product gets its own row. The search usesnamefor the same reason: by default Locust names a request by its path including the query string.
Run it without the web interface for 15 seconds: 20 users, started 5 per second, against the shop:
uv run locust -f locustfile.py --headless --users 20 --spawn-rate 5 --run-time 15s --host http://127.0.0.1:8000 --only-summary--only-summary stops Locust printing a table every few seconds and prints one at the end instead.
Check it worked
The run ends with a table of request rows: POST /api/login, GET /api/products, GET /api/products/[id], GET /api/search, POST /api/cart and an Aggregated total. /api/login shows 20 requests, one per user. The # fails column is 0 everywhere and the last log line says something like Shutting down (exit code 0).
Yet you know that one search in ten returned an error. Locust counted those as successes because the status was 200. The next step fixes that.
Step 4 · Mark bad answers as failures
By default Locust treats any status below 400 as a success. When a correct status can carry a wrong answer, pass catch_response=True and decide yourself. Inside the with block, response.failure("reason") records a failure and response.success() records a success. If you call neither, the status code decides, as before.
Replace locustfile.py with this version. Sign-in and search now check the body:
cat > locustfile.py <<'PY'
import os
import random
from locust import HttpUser, between, task
PASSWORD = os.environ.get("SHOP_PASSWORD")
if not PASSWORD:
raise SystemExit("Set SHOP_PASSWORD before running Locust.")
PRODUCT_IDS = list(range(1, 21))
SEARCH_TERMS = ["lamp", "mug", "phone", "bag"]
class Shopper(HttpUser):
wait_time = between(1, 3)
def on_start(self):
with self.client.post(
"/api/login",
json={"username": "shopper", "password": PASSWORD},
catch_response=True,
) as response:
token = response.json().get("token") if response.ok else None
if not token:
response.failure(f"sign-in refused with status {response.status_code}")
return
self.client.headers["Authorization"] = f"Bearer {token}"
@task(6)
def browse(self):
self.client.get("/api/products")
@task(3)
def view_product(self):
product_id = random.choice(PRODUCT_IDS)
self.client.get(f"/api/products/{product_id}", name="/api/products/[id]")
@task(2)
def search(self):
term = random.choice(SEARCH_TERMS)
with self.client.get(
"/api/search", params={"q": term}, name="/api/search", catch_response=True
) as response:
if response.ok and "error" in response.json():
response.failure(f"search error: {response.json()['error']}")
@task(1)
def add_to_cart(self):
product_id = random.choice(PRODUCT_IDS)
self.client.post("/api/cart", json={"product_id": product_id, "quantity": 1})
PYRun the same test again and print the exit code:
uv run locust -f locustfile.py --headless --users 20 --spawn-rate 5 --run-time 15s --host http://127.0.0.1:8000 --only-summary
echo "exit code: $?"Check it worked
The GET /api/search row now has failures, roughly one in ten of its requests, and every other row still shows 0. Below the table, an error report lists search error: search index busy with its count. The last line says exit code: 1.
That exit code comes from Locust's default rule: any failure at all makes the process exit with 1 (change the number with --exit-code-on-error). For a gate in a pipeline that is usually too strict. A busy production system has a small background error rate, and what you care about is whether it stays under a limit.
Step 5 · Turn the results into a pass or fail
Locust fires a quitting event just before it exits, with the final statistics in environment.stats. A listener can read them and set environment.process_exit_code, which overrides the default rule. Two more listeners on init_command_line_parser add your limits as command-line options, so you can tighten them per run without editing code.
Append this to locustfile.py:
cat >> locustfile.py <<'PY'
import logging
from locust import events
@events.init_command_line_parser.add_listener
def add_limits(parser):
parser.add_argument("--max-fail-ratio", type=float, default=0.05,
help="Fail the run above this share of failed requests (0.05 = 5%%)")
parser.add_argument("--max-p95-ms", type=int, default=500,
help="Fail the run if the 95th percentile response time is above this")
@events.quitting.add_listener
def check_limits(environment, **kwargs):
total = environment.stats.total
limits = environment.parsed_options
p95 = total.get_response_time_percentile(0.95)
if total.fail_ratio > limits.max_fail_ratio:
logging.error("FAIL: %.1f%% of requests failed, limit %.1f%%",
total.fail_ratio * 100, limits.max_fail_ratio * 100)
environment.process_exit_code = 1
elif p95 > limits.max_p95_ms:
logging.error("FAIL: p95 is %d ms, limit %d ms", p95, limits.max_p95_ms)
environment.process_exit_code = 1
else:
logging.info("PASS: %.1f%% failed, p95 %d ms", total.fail_ratio * 100, p95)
environment.process_exit_code = 0
PYThe p95 is the response time that 95% of requests beat. It shows what your slower users feel, which an average hides. Reading load test results explains why it matters more than the mean.
Run with the default limits, 5% failures and a p95 of 500 ms:
uv run locust -f locustfile.py --headless --users 20 --spawn-rate 5 --run-time 15s --host http://127.0.0.1:8000 --only-summaryThen run with no failures allowed at all:
uv run locust -f locustfile.py --headless --users 20 --spawn-rate 5 --run-time 15s --host http://127.0.0.1:8000 --only-summary --max-fail-ratio 0
echo "exit code: $?"Check it worked
The first run still shows search failures in the table, but ends with a line like PASS: 1.4% failed, p95 75 ms and exit code 0: about 1.5% of all requests fail, under the 5% limit. The second run ends with FAIL: 1.4% of requests failed, limit 0.0% and exit code: 1. Your exact numbers differ a little each run because tasks and waits are random.
In a CI job, the exit code is all the pipeline needs: 0 passes the job, anything else fails it.
Step 6 · Save the results as CSV
The summary table scrolls away. --csv results writes the numbers to files that start with results, so you can keep them as a build artefact, compare runs or chart them. Run a 30-second test with CSV output:
uv run locust -f locustfile.py --headless --users 20 --spawn-rate 5 --run-time 30s --host http://127.0.0.1:8000 --only-summary --csv results
ls results_*.csvLocust writes four files:
results_stats.csv: one row per request name plus anAggregatedrow, with counts, failures, average and median times, requests per second and percentiles from 50% to 100%.results_stats_history.csv: the same totals sampled every few seconds during the run, which shows whether latency crept up as users arrived.results_failures.csv: each distinct failure with its count.results_exceptions.csv: Python exceptions raised in your locustfile. It should be empty apart from the header.
Read the main file with a short script:
cat > report.py <<'PY'
import csv
with open("results_stats.csv", newline="") as f:
for row in csv.DictReader(f):
print(f"{row['Name']:<22} {row['Request Count']:>6} reqs "
f"{row['Failure Count']:>4} fails p95 {row['95%']:>4} ms")
PY
uv run report.pyCheck it worked
The report prints six lines, one per route plus Aggregated. /api/login has 20 requests and 0 failures, /api/search is the only row with failures, and /api/products/[id] has a higher p95 than /api/products because of its database-like delay. Open results_failures.csv and you see the search error with its count.
Step 7 · Use the web UI and spread load across workers
Two ways of running Locust are worth knowing even though a pipeline uses neither.
The web UI. Leave out --headless and Locust starts a web interface on port 8089:
uv run locust -f locustfile.py --host http://127.0.0.1:8000Open http://localhost:8089, enter a number of users and a spawn rate, and start. You get live charts of requests per second, response times and user count, and you can raise the user count during the run. That makes it good for exploring: add users until response times bend upwards, and you have found roughly where the app starts to struggle.
Distributed mode. One Locust process uses one CPU core. When the load generator itself runs out of CPU (Locust logs a warning when it is above 90%), add worker processes. On one machine with several cores, --processes forks workers for you, here four of them (it is marked experimental and does not work on Windows):
uv run locust -f locustfile.py --headless --users 500 --spawn-rate 50 --run-time 5m --host http://127.0.0.1:8000 --processes 4Across machines, start one master and point workers at it. Every machine needs the same locustfile and the same SHOP_PASSWORD. Replace 10.0.0.5 with your master's address and 10.0.0.20:8000 with your app's address:
# On the master machine
uv run locust -f locustfile.py --master --headless --expect-workers 2 --users 500 --spawn-rate 50 --run-time 5m --host http://10.0.0.20:8000
# On each worker machine
uv run locust -f locustfile.py --worker --master-host 10.0.0.5The master waits for two workers, shares the users between them, collects their statistics and runs your quitting check on the combined totals.
A note on realistic load: if many of your users are on prepaid mobile data or low-end Android phones, as is common across Africa, each request is held open longer and pages are fetched more slowly than from a fibre connection. Run the load generator from a machine whose network looks like your users' where you can, and keep think time honest rather than lowering it to get bigger numbers.
Check it worked
With the web UI command running, http://localhost:8089 shows a form asking for the number of users and the ramp up. Stop it with Ctrl+C. For distributed runs, the master's log lists each worker as it connects, and the summary table at the end covers all of them.
Step 8 · Clean up
Stop the shop with Ctrl+C in the second terminal. Then remove the demo project and clear the practice password from both terminals. Python and uv stay installed:
cd ~
rm -rf ~/locust-demo
unset SHOP_PASSWORDCheck it worked
ls ~/locust-demo reports that there is no such file or directory, and nothing answers on port 8000.
Next steps
- Write the same kind of test in JavaScript, with thresholds built into the tool: load test an API with k6.
- Make sense of the numbers you just collected: read load test results: percentiles, throughput and saturation.
- Keep Locust's version pinned per project: Python virtual environments and packages.
Related tutorials
- Write unit tests that stay useful as the code changesYou will replace a brittle pytest suite with behaviour tests that catch a real boundary bug and stay green when the code under them is rewritten.
- Write property-based tests in TypeScript with fast-checkYou will use fast-check and Vitest to find a rounding bug in a TypeScript money module, replay the failure from its seed, fix it, and model-test a shopping cart with generated command sequences.
- Write negative tests for an API: bad input, auth and limitsYou will build a pytest and httpx suite that attacks a small FastAPI ordering API with missing and extra fields, wrong types, boundary values, long and multilingual text, bad tokens, another user's data, rate limits and reused idempotency keys, and proves every error comes back in one RFC 9457 format.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials