You’re going to write your first Locustfile, and the most surprising thing is how little code it actually takes to simulate thousands of users.
Let’s see it in action. Imagine we want to hit an API endpoint /users and check if we get a 200 OK. Here’s the entire Locustfile for that:
from locust import HttpUser, task, between
class WebsiteUser(HttpUser):
wait_time = between(1, 5) # Users will wait 1-5 seconds between tasks
host = "http://localhost:8080" # Target host
@task
def get_users(self):
self.client.get("/users")
That’s it. You can run this with locust -f your_locustfile_name.py. Locust will start a web UI on port 8089 where you can specify the number of users and the spawn rate, and then hit "Start swarming."
What problem does this solve? It lets you easily simulate load against an HTTP service to see how it performs under stress. You can test performance bottlenecks, identify slow endpoints, and understand how many users your service can handle before things break.
How does it work internally? Locust is built on Python’s asyncio for efficient concurrency. When you define a task within a User class, you’re telling Locust what actions a simulated user should perform. The HttpUser class specifically provides a client attribute, which is an instance of HttpSession (a wrapper around requests that automatically handles cookies, redirects, and other HTTP niceties). The wait_time defines the pause between executing tasks, making the simulation more realistic. You can define multiple tasks, and Locust will randomly pick one for each user to execute.
The exact levers you control are primarily in the User class. wait_time is crucial for simulating realistic user behavior; between(1, 5) means each user will wait between 1 and 5 seconds before executing their next task. The host variable sets the base URL for all requests made by this user class. You can define multiple User classes to simulate different types of users with different behaviors and target different hosts. For more complex scenarios, you can use tasksets to define sequences of tasks or conditional logic.
The HttpSession client automatically accumulates statistics. When you run Locust, the web UI shows you metrics like requests per second, response times (average, median, 95th percentile), and failure rates. This data is aggregated across all your simulated users and is the core output you use to analyze performance.
Many people think Locust is just for simple GET requests. You can actually simulate complex user flows that involve chaining requests, checking responses, and even using data from previous requests in subsequent ones. For example, you might log in, get a user ID, and then use that ID to fetch specific user data. This is done by defining multiple tasks within a taskset or by calling other tasks from within a task.
The next concept you’ll likely explore is defining more complex user behaviors with tasksets and event hooks.