
A checkout API can return HTTP 200 on every request while customers wait too long for a price, or see the wrong price altogether. A useful Locust load test measures how long that step takes and checks what the customer actually receives. Both checks matter when you’re deciding whether to change the application or give it a larger CPU VM.
In this example, four simulated shoppers read a catalog and request a quote. Adding a 120 ms delay to the quote moved its 95th-percentile response time from 7 ms to 130 ms. Catalog latency barely moved. Here’s how to reproduce that difference and find it in the results.
Locust runs a Python class for each simulated user. Our shopper reads /catalog, then calls /quote, then waits a quarter of a second before repeating the pair. Putting both requests in one task preserves their order. If you make them independent randomly selected tasks, you answer a different question about the application.
Choose a success condition before running the test. Our catalog must respond successfully and the quote must return the fixture price of 1,200 cents. On a real checkout, derive the expected price from a known test product. Comparing response times alone would miss a fast answer with the wrong amount.
We used Python 3.12.14 and Locust 2.47.0 on Windows. In an activated Python virtual environment, install the tested release. Save the following files in the same directory.
python -m pip install locust==2.47.0
Save this as api.py. It serves two routes on the loopback interface. The quote delay models a request waiting for a dependency, an important distinction when interpreting CPU use.
import argparse
import json
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
parser = argparse.ArgumentParser()
parser.add_argument("--port", type=int, default=8765)
parser.add_argument("--quote-delay-ms", type=int, default=0, choices=range(1001),
metavar="0..1000")
parser.add_argument("--invalid-quote", action="store_true")
options = parser.parse_args()
class API(BaseHTTPRequestHandler):
def do_GET(self):
status = 200
if self.path == "/catalog":
body = {"items": ["notebook"]}
elif self.path == "/quote":
time.sleep(options.quote_delay_ms / 1000)
body = {"price_cents": 0 if options.invalid_quote else 1200}
else:
status, body = 404, {"error": "unknown route"}
payload = json.dumps(body).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
def log_message(self, *args):
pass
if __name__ == "__main__":
with ThreadingHTTPServer(("127.0.0.1", options.port), API) as server:
print(server.server_port, flush=True)
server.serve_forever()
Run python api.py in the first terminal and leave it running. The server prints its port, 8765 by default.
Save this as locustfile.py. Locust records each route separately. The quote uses catch_response=True so the application-level check can mark an incorrect HTTP 200 response as failed. A connection error or unsuccessful HTTP status still follows Locust’s usual handling. Locust’s guide to writing a user class
from locust import HttpUser, constant, task
class Shopper(HttpUser):
host = "http://127.0.0.1:8765"
wait_time = constant(0.25)
@task
def browse_and_quote(self):
self.client.get("/catalog", timeout=2)
with self.client.get("/quote", timeout=2, catch_response=True) as response:
if response.status_code == 200:
try:
valid = response.json().get("price_cents") == 1200
except (ValueError, AttributeError):
valid = False
if not valid:
response.failure("unexpected quote")
In a second terminal, activate the same environment and run the command below. -u 4 sets the target number of users, -r 4 starts up to four users per second, and -t 15s bounds the run. The spawn rate controls how quickly users start. Each shopper’s response times and pause then determine how quickly it makes requests. Locust’s headless run options
python -m locust -f locustfile.py --headless -u 4 -r 4 -t 15s --csv baseline --only-summary
Once the run finishes, stop the API with Ctrl+C. Restart it with python api.py --quote-delay-ms 120. Repeat the same workload with a different CSV prefix so you can compare the two reports.
python -m locust -f locustfile.py --headless -u 4 -r 4 -t 15s --csv slow --only-summary
Open baseline_stats.csv and slow_stats.csv. Read the 95% column for each route, then read Requests/s and Failure Count on the Aggregated row. The p95 is the response time at or below which roughly 95% of recorded requests for that row finished. A short run is enough to see an injected delay. It gives a weak estimate of rare slow requests. Locust’s CSV output reference
All four shoppers had to wait for the slower quote before starting another cycle. That explains why throughput fell despite an identical command. This is a closed workload: the users already in the system generate the next requests. If your requirement specifies a fixed arrival rate even as responses slow down, the FastAPI deployment guide includes a k6 example for that case.
Stop the API and run python api.py --invalid-quote. This returns zero cents with HTTP 200 for every quote. Run a short control with a third CSV prefix.
python -m locust -f locustfile.py --headless -u 4 -r 4 -t 5s --csv invalid --only-summary
In our run, all 64 quotes failed the price check, and all 64 catalog requests succeeded. Locust returned exit code 1. Open invalid_failures.csv and look for unexpected quote. That result shows the workload can detect the specific fault you introduced. A zero failure count in the first two trials carries more weight once you know this check works.
Start with the route that changed. Here the quote handler deliberately slept. Buying more CPU would leave that wait in place. On your own service, compare route latency with dependency timing, worker queues, and CPU use over the same interval. If only requests that call one dependency slow down, measure that dependency before resizing the VM.
When CPU use stays high across the workers and queue time grows, repeat the same workload on a larger CPU instance from Compute with Hivenet. Keep the application build, dataset, worker settings and client pacing fixed. Run the generator on a separate machine, allow the service to warm up, and repeat each measurement. Our local client and API shared one computer. Their throughput figures describe this exercise only.
If you already distribute traffic across several backends, check the per-backend request counts before adding another instance. A busy worker and an idle peer can produce a slow aggregate even with spare capacity. The Nginx load balancing guide shows how to identify which upstream answered.
Pick one AI, compute, or storage workload and see the difference for yourself. Spin it up in minutes, or let our team map your fastest path to production.