Locust Load Testing: Complete Beginner's Guide

Locust Load Testing: Complete Beginner's Guide

Locust is an open-source Python load testing tool where you define user behavior in plain Python code. This guide walks you from zero to running your first load test: install Locust, write a locustfile, execute it against a real API, and interpret the results dashboard. By the end you'll understand key metrics like RPS, response times, and failure rates.

Load testing is one of those practices that teams know they should do but perpetually defer. The tooling feels intimidating, the setup seems complex, and there's always something more urgent on the backlog. Locust changes that calculus. It's a Python-native tool that lets you describe load test scenarios as ordinary code, run them from a browser-based UI, and get actionable metrics within minutes.

This guide is for developers who have never run a load test before. We'll go from a fresh machine to a complete load test run against a sample API, reading every number in the results dashboard.

What Is Locust and Why Does It Matter?

Locust is an open-source load testing framework written in Python. Unlike GUI-based tools like JMeter, Locust scenarios are pure Python — you write a class, define HTTP calls, and Locust handles simulating thousands of concurrent users, tracking response times, and calculating error rates.

The name is intentional. Locusts swarm. The tool sends swarms of simulated users at your system to see what breaks.

Key characteristics:

  • Python all the way down — no XML config, no special DSL, just Python classes
  • Browser-based UI — start/stop tests and watch live charts without touching the terminal
  • Headless mode — run from CI with --headless flag for automated pipelines
  • Distributed out of the box — add worker nodes to generate more load
  • Extensible — override the HTTP client, add custom protocols, hook into events

Installation

Locust requires Python 3.9 or later. Install it with pip:

pip install locust

Verify the installation:

locust --version
# locust 2.x.x

For isolated environments (recommended), use a virtual environment:

python -m venv venv
source venv/bin/activate   # Windows: venv\Scripts\activate
pip install locust

That's it. No Java runtime, no Docker daemon, no external services. Locust is a single Python package.

Your First Locustfile

A locustfile is a Python module that Locust looks for by default at locustfile.py in your current directory. Create one now:

from locust import HttpUser, task, between

class WebsiteUser(HttpUser):
    wait_time = between(1, 3)

    @task
    def browse_homepage(self):
        self.client.get("/")

    @task(3)
    def browse_products(self):
        self.client.get("/api/products")

    @task(1)
    def view_single_product(self):
        self.client.get("/api/products/1")

Let's unpack every line:

HttpUser is the base class for users that make HTTP requests. Locust provides self.client, a requests-compatible session object. Every simulated user is an instance of this class.

wait_time = between(1, 3) defines how long each simulated user waits between tasks. between(1, 3) means a random pause between 1 and 3 seconds. This models realistic user behavior — real users don't hammer APIs as fast as possible.

@task marks a method as a task. Locust randomly picks tasks to execute for each user. The optional integer argument is the weight — @task(3) means this task runs three times as often as an unweighted @task.

self.client.get("/api/products") makes an HTTP GET request. The host is specified separately when you start Locust, not in the locustfile. This separation lets you run the same scenario against staging and production.

Running Locust

With the Web UI

Start Locust from the directory containing your locustfile.py:

locust --host https://your-api.example.com

Open your browser at http://localhost:8089. You'll see a form asking for:

  • Number of users: peak concurrent users to simulate
  • Spawn rate: users to add per second until the peak is reached
  • Host: pre-filled from --host, but editable

Enter 50 users, spawn rate 5, and click Start Swarming. Locust ramps up 5 users per second until all 50 are active, then maintains that load until you stop.

With Headless Mode

For CI pipelines or scripted runs:

locust \
  --headless \
  --users 50 \
  --spawn-rate 5 \
  --run-time 60s \
  --host https://your-api.example.com \
  --csv results

--run-time 60s stops the test automatically after 60 seconds. --csv results writes results_stats.csv and results_failures.csv to disk.

Understanding the Results

The Statistics Table

The web UI's Statistics tab shows a table with one row per request type. For each row:

Column Meaning
# Requests Total requests made so far
# Fails Requests that returned an error (4xx/5xx or timeout)
Median (ms) 50th percentile response time
90%ile (ms) 90th percentile — 90% of requests were faster than this
99%ile (ms) 99th percentile — the "worst" 1%
Average (ms) Mean response time (less useful than percentiles)
Min / Max Fastest and slowest individual requests
Current RPS Requests per second at this moment
Current Failures/s Error rate at this moment

The 90th and 99th percentiles matter most. Your average can look fine while your P99 reveals that 1% of users wait 10 seconds. Users in that 1% are the ones leaving bad reviews.

A healthy load test shows:

  • Failure rate near 0%
  • P95 response time within your SLA (commonly < 500ms for APIs)
  • Stable RPS as user count increases

The Charts Tab

Three live charts update every few seconds:

  1. Total Requests per Second — your system's throughput. A flat line is good. A dropping line under stable user count means your system is struggling.
  2. Response Times (ms) — plots median and P95. Watch for these to climb as load increases; the inflection point is your saturation threshold.
  3. Number of Users — the ramp-up curve.

The Failures Tab

Every failed request is listed with its URL, HTTP method, response code, and error message. Even a 0.1% failure rate worth investigating in production. The failures tab tells you exactly which endpoints are misbehaving.

Adding Authentication

Most real APIs require authentication. Add it in the on_start method, which runs once per simulated user before any tasks:

from locust import HttpUser, task, between

class AuthenticatedUser(HttpUser):
    wait_time = between(1, 2)

    def on_start(self):
        response = self.client.post("/api/auth/login", json={
            "username": "testuser",
            "password": "testpass"
        })
        token = response.json()["access_token"]
        self.client.headers.update({"Authorization": f"Bearer {token}"})

    @task
    def get_profile(self):
        self.client.get("/api/profile")

    @task(2)
    def list_orders(self):
        self.client.get("/api/orders")

self.client is a persistent session, so headers set in on_start persist across all subsequent requests for that user.

Grouping Requests by Name

By default, Locust groups results by URL. If your API uses path parameters like /api/users/123, each unique user ID creates a separate row in the statistics table. Group them:

@task
def view_user(self):
    user_id = random.randint(1, 1000)
    self.client.get(f"/api/users/{user_id}", name="/api/users/[id]")

The name parameter collapses all variations into a single row.

Asserting Response Content

The HTTP client doesn't automatically fail requests that return incorrect data — it only looks at HTTP status codes. For content validation, catch failures explicitly:

@task
def get_products(self):
    with self.client.get("/api/products", catch_response=True) as response:
        if response.status_code != 200:
            response.failure(f"Unexpected status: {response.status_code}")
        elif "items" not in response.json():
            response.failure("Response missing 'items' field")
        else:
            response.success()

catch_response=True gives you a context manager. Call response.failure() to manually mark a request as failed even if the HTTP status was 200.

Common Patterns

Sequential tasks (user flow)

from locust import HttpUser, task, between, SequentialTaskSet

class CheckoutFlow(SequentialTaskSet):
    @task
    def add_to_cart(self):
        self.client.post("/api/cart", json={"product_id": 42, "qty": 1})

    @task
    def view_cart(self):
        self.client.get("/api/cart")

    @task
    def checkout(self):
        self.client.post("/api/checkout", json={"payment": "card"})

class ShopUser(HttpUser):
    tasks = [CheckoutFlow]
    wait_time = between(2, 5)

SequentialTaskSet executes tasks in the order they're defined, which is essential for flows where step 2 depends on step 1.

Parametrizing from a file

import csv
import random

with open("users.csv") as f:
    TEST_USERS = list(csv.DictReader(f))

class LoadUser(HttpUser):
    wait_time = between(1, 2)

    def on_start(self):
        creds = random.choice(TEST_USERS)
        self.client.post("/login", data=creds)

What to Test

A beginner load test should answer three questions:

  1. Can the system handle expected load? Run with the number of concurrent users you expect at peak. If P95 response time stays under your SLA with zero failures, you're good.
  2. What's the breaking point? Gradually increase users until failure rate climbs above 1% or response times blow your SLA. This is your capacity ceiling.
  3. Does the system recover? After hitting the ceiling, ramp back down to normal load. Response times should return to baseline within a minute or two. Systems that don't recover have resource leak bugs.

Reading CSV Output

The --csv flag produces two files:

results_stats.csv — aggregate stats per endpoint:

Type,Name,Request Count,Failure Count,Median Response Time,Average Response Time,Min Response Time,Max Response Time,Average Content Size,Requests/s,Failures/s,50%,66%,75%,80%,90%,95%,98%,99%,99.9%,99.99%,100%
GET,/api/products,4521,0,142,148,89,1203,1024,75.35,0.00,142,155,163,168,192,213,245,278,612,1203,1203

results_failures.csv — every unique failure:

Method,Name,Error,Occurrences
GET,/api/products,ConnectionError(...),3

Parse these in your CI pipeline to assert SLA compliance programmatically.

Next Steps

You've installed Locust, written a locustfile with weighted tasks, run a test with the web UI and headless mode, and know how to read every column in the results dashboard. From here:

  • Custom load shapes — ramp-up curves, spike tests, and soak tests using LoadTestShape
  • Distributed testing — run master/worker setups when a single machine can't generate enough load
  • CI integration — fail builds automatically when P95 response time exceeds your SLA
  • Non-HTTP protocols — test WebSockets, gRPC, or databases by extending the base User class

Load testing is a habit, not a one-time event. The teams who catch performance regressions early are the ones who run Locust on every significant deployment.

Read more

Start now free