A backend developer at a fintech startup had a payments API that passed every functional test. Then a promotion went live, 3,000 people hit checkout in ten minutes, and response times jumped from 300 milliseconds to 9 seconds. The code was fine; the system had simply never been tested with that many users at once.
That system was missing load testing. Locust load testing is a simple way to start, and this guide walks you through it step by step. By the end, you will know how your web applications handle real user behaviour.
What Is Locust Load Testing?
Locust is an open-source load testing tool written in Python. You use it to simulate large numbers of users hitting your website, API, or other system, so you can see how it performs under stress before real traffic does it for you.
Teams run it before launches and busy periods. Three points explain it.
- How it works: Simulated users follow a Python script, sending requests and pausing like real visitors, while Locust ramps up users and records timings and failures.
- Where it fits: Among performance testing tools and performance testing software, this load testing software suits Python teams, since Python load testing needs no new language.
- What it does not cover: It is not a security solution. A security service blocks online attacks, while Locust shows how your site copes with legitimate traffic, which every site owner should know.
Locust vs JMeter vs k6
Apache JMeter uses a GUI and XML plans for JMeter load testing and JMeter performance testing, while the k6 load testing tool uses JavaScript for k6 performance testing. Locust uses Python. The table compares them.
Core Features & Advantages of Locust Load Testing
Locust keeps load testing in readable code. Five features cover most of what beginners need.
- User scenarios as code: Write test steps in Python that send HTTP requests through an API client, instead of XML or GUI settings.
- Live web UI: Watch concurrent users, requests per second, response time, and error rate update in real time.
- Distributed mode: One master coordinates many workers, so distributed load generation can power large-scale load tests, including on Cloud Computing platforms like Microsoft Azure.
- Lightweight users: Each user is a gevent greenlet, not an operating system thread, so memory stays low.
- Detailed reporting: CSV and HTML output lets you compare runs, and more users turn the same script into stress testing software.
How to Install Locust
This section walks you through checking Python 3 and pip, creating an isolated environment, and installing the load testing framework.
Installing Locust with pip
Use a virtual environment so Locust stays separate from your system Python.
python -m venv locust-env
# On macOS / Linux
source locust-env/bin/activate
# On Windows
locust-env\Scripts\activate
pip install locust
locust --versionA version number means Locust Python is ready.
Checking Your Python Version and Setup
Locust needs a recent Python 3 release, so confirm the current minimum in the Locust documentation. Check both tools first:
python --version
pip --versionIf either is missing, install Python, which includes pip:
# macOS (Homebrew)
brew install python
# Ubuntu or Debian
sudo apt install python3 python3-pip python3-venv
# Windows: download from python.org and tick "Add Python to PATH"Reopen your terminal, then fix the usual errors:
- python not found: Try python3 and pip3.
- locust not found: Activate the virtual environment again.
How to Write Your First Locust Test
A Locust test lives in a single Python file, usually called locustfile.py. In it, you describe one type of visitor and the actions that visitor takes, and Locust then creates many copies of that visitor and runs them all at once.
Setting Up a Test Application
You need something to test. JSON Server turns a db.json file into a working REST API, and it only needs Node.js. JSON Server Auth can add logins later. Create db.json in a new folder:
{
"products": [
{"id": 1, "name": "Keyboard", "price": 49},
{"id": 2, "name": "Mouse", "price": 25}
],
"orders": []
}Start the API in a second terminal and leave it running:
npm install -g json-server@0.17.4
json-server --watch db.json --port 3000Check it with curl http://localhost:3000/products, which should return both products. This local server is only a learning target, so its numbers say nothing about your real system.
Writing a Basic locustfile.py
Save this as locustfile.py in the same folder:
from locust import HttpUser, task, between
class ShopUser(HttpUser):
wait_time = between(1, 3)
@task
def view_products(self):
self.client.get("/products")Here is what each part does:
- The user class: ShopUser represents one visitor. Because it extends HttpUser, each simulated user gets self.client, an HTTP client that sends requests and records how long each one takes.
- The wait time: between(1, 3) makes each user pause one to three seconds between actions. Without it, users fire requests nonstop, which is far heavier than real user behaviour.
- The task: A method marked with @task is an action the user performs. Locust runs it repeatedly.
That is the whole test, which is why Python Locust scripts feel approachable. The same pattern works for REST API testing, although Locust is a load testing tool, not a full API testing suite.
Adding Tasks and Weights
Real users do some things far more often than others, and task weights express that mix. Replace your locustfile.py with this complete version:
from locust import HttpUser, task, between
class ShopUser(HttpUser):
wait_time = between(1, 3)
@task(5)
def browse_products(self):
with self.client.get("/products", catch_response=True) as response:
if response.status_code == 200 and len(response.text) < 3:
response.failure("Product list was empty")
@task(1)
def place_order(self):
self.client.post("/orders", json={"productId": 1})The number inside @task() is the weight. With weights of 5 and 1, browsing runs five times for every order. The catch_response check marks a request as failed when the server returns 200, but the content is wrong, which a status code alone would miss. Here, an empty list comes back as [], which is only two characters long.
How to Run Your First Locust Load Test
Locust runs in two modes. The web UI is for exploring, and headless mode is for automation.
Running Tests from the Locust Web UI
In your first terminal, start Locust from the folder holding locustfile.py, while JSON Server keeps running in the second. Point Locust at your target with --host.
locust -f locustfile.py --host http://localhost:3000Then open http://localhost:8089, fill in the two values below, and click Start. The host is already filled in from the --host flag. Labels vary by version, so check them against your release.
- Users: How many concurrent users to simulate. Try 50.
- Spawn rate: How many new users start per second, also called the ramp-up rate. Try 5.
Watch the Statistics and Charts tabs, let the test run for a minute or two, then press Stop.
Every POST /orders adds a record to db.json, so reset the orders list to [] before each new run to keep results comparable.
Once the settings work, save them in a locust.conf file in the same folder. Locust reads it automatically, so every rerun uses the same test configurations.
locustfile = locustfile.py
host = http://localhost:3000
users = 50
spawn-rate = 5
run-time = 2m
headless = trueDrop the headless and run-time lines if you want to keep using the web UI.
Running Locust Headless in a CI Pipeline
Headless mode drops the browser and takes everything from flags. That suits CI/CD pipelines such as GitHub Actions or Jenkins, and our guide to test automation in CI/CD covers the wider pattern.
locust -f locustfile.py --headless -u 100 -r 10 -t 2m \
--host http://localhost:3000 --csv results --html report.htmlAfter two minutes, it prints a summary table and writes results_stats.csv and report.html to the folder.
- -u sets users, -r sets the spawn rate, -t sets the duration.
- --csv and --html save results so the pipeline can keep them.
- In Jenkins, a Performance Plugin can chart saved results across builds, if your version reads the format.
Reading Locust Results: RPS, Response Times, Failures
Three numbers carry most of the story.
- Requests per second (RPS): Throughput.
- Response time: Read it as percentiles. The median is the typical visit; the 95th percentile is the unlucky one in twenty.
- Error rate: The share of requests that failed.
RPS climbs with users, then holds, while percentiles stay steady and the error rate stays near zero. A degrading run shows RPS plateauing while response times keep rising, and that plateau is your limit. Then ask where the time goes:
- The load balancer, if requests queue before reaching servers.
- The caching layer, if hit rates drop under load.
- Database load, often a single slow query.
- The HTTP server, if workers or threads run out.
Those findings feed capacity planning. You learn how many users you can serve now and what to add before launch.
Locust Load Testing: Live Terminal Walkthrough
Common Locust Mistakes
A team once reported that their API handled 5,000 users easily, but the test ran from an underpowered laptop with no wait times. Three mistakes cause most bad results like this:
- Unrealistic user behaviour: Missing wait times and one-endpoint scripts flood the server in ways no customer would.
- An underpowered load generator: If the machine running Locust maxes out its CPU, results measure that machine.
- No permission: Test only what you are cleared to test. A site owner may need to warn their host, and a security service can mistake heavy traffic for online attacks and block it, even though real attacks send things like a SQL command or malformed data.
How Frugal Testing Helps You Run Locust Load Tests Without the Overhead
Locust is free, but doing it well takes time most teams lack. That is where our load testing services come in. We design the scenarios, run tests from properly sized infrastructure, and give you a report your team can act on.
Our performance testing services and software performance testing services cover performance/load testing end to end, and our api testing services cover the REST endpoints behind it, using api testing tools for automated api testing. When you compare a quality assurance testing company, or search for the best software testing company, ask who writes the scripts and who owns them afterwards.
What Our Load Testing Engagement Looks Like
- Week 1: Agree on user journeys, targets, and success thresholds, then set up a test environment.
- Week 2: Write and review the locustfile in Python, then run a small smoke test.
- Week 3: Run baseline, load, and spike tests in a safe environment.
- Week 4: Share findings ranked by impact, with the scripts and a walkthrough call.
.webp)
Conclusion
Locust load testing rewards a small, honest start. Write a simple script in Python, run it against a safe target, and read the percentiles and error rate before adding more users. A modest test you trust is worth more than a huge one you cannot explain.
Once that habit is in place, make it routine. Run a short test in CI every week, keep the results, and watch how your limit moves as the code changes. If you want a second pair of hands, our team can help you set it up.
People Also Ask (FAQs)
Q1. What user count should I start with in a first Locust test?
Ans: Start small, around 10 to 50 users, confirm the script works and the server stays healthy, then raise the number in steps until response times or errors begin climbing.
Q2. Which response time target is reasonable for a web app?
Ans: It depends on your users, but many teams aim for a 95th percentile under two seconds and an error rate near zero. Agree on targets with your business before testing.
Q3. Where should I run a load test, staging or production?
Ans: Use a staging environment that mirrors production, with similar data and hardware. Testing production risks real customers, so do it only with approval and off-peak hours.
Q4. What is load testing, and how is it different from stress testing?
Ans: Load testing checks how a system behaves at expected traffic. Stress testing pushes past that level until the system fails, showing where it breaks and how it recovers.
Q5. Will a failed Locust test stop my CI build?
Ans: Yes, Locust exits with a non-zero code when requests fail, so a CI job can fail the build. Check the documentation's exit-code flags to tune what counts as a failure.





