Locust Custom Users and Tasks: Advanced Locustfile Patterns

Locust Custom Users and Tasks: Advanced Locustfile Patterns

Locust tasks are Python methods decorated with @task. Custom users extend HttpUser to define wait times, task sets, and HTTP client behavior. This guide covers task weights, sequential flows, on_start/on_stop hooks, custom clients for WebSockets or gRPC, and realistic user simulation patterns.

A load test is only as good as its scenario. Hammering a single endpoint with uniform requests tells you nothing about real user behavior—users log in, browse, add items to carts, and check out in sequences. Locust's task model gives you full Python expressiveness to model these flows accurately.

The Task Model: Core Concepts

Every Locust test defines at least one User class with task-decorated methods:

from locust import HttpUser, task, between

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

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

    @task
    def view_product(self):
        self.client.get("/api/products/123")

Locust runs each simulated user in a loop: pick a task, execute it, wait between wait_time bounds, repeat. The @task decorator registers methods as executable tasks.

Task Weights

Not all tasks are equally common. A real e-commerce site sees 10x more product views than checkouts. Task weights model this:

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

    @task(10)  # 10x more likely than checkout
    def browse_products(self):
        self.client.get("/api/products")

    @task(5)
    def view_product(self):
        product_id = random.randint(1, 1000)
        self.client.get(f"/api/products/{product_id}")

    @task(2)
    def add_to_cart(self):
        self.client.post("/api/cart", json={"product_id": 123, "qty": 1})

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

Locust picks tasks randomly with probability proportional to weight. With weights 10:5:2:1, browse_products runs roughly 56% of the time, checkout about 6%.

Sequential Task Flows

Sometimes tasks must happen in order: login → get products → add to cart → checkout. Use TaskSet for sequential flows:

from locust import HttpUser, TaskSet, task, between

class CheckoutFlow(TaskSet):

    def on_start(self):
        """Called once when a user starts this TaskSet."""
        resp = self.client.post("/api/auth/login", json={
            "email": "test@example.com",
            "password": "password123"
        })
        self.token = resp.json()["token"]

    @task
    def add_to_cart(self):
        self.client.post(
            "/api/cart",
            json={"product_id": 1},
            headers={"Authorization": f"Bearer {self.token}"}
        )
        # Move to checkout immediately
        self.checkout()

    def checkout(self):
        self.client.post(
            "/api/orders",
            json={"payment": "stripe"},
            headers={"Authorization": f"Bearer {self.token}"}
        )
        self.interrupt()  # Return to parent user class

class ShopUser(HttpUser):
    wait_time = between(1, 3)
    tasks = [CheckoutFlow]

self.interrupt() exits the TaskSet and returns control to the parent user's task picker.

The on_start and on_stop Hooks

on_start runs once per user when they "spawn." on_stop runs when the test ends or the user stops. These are ideal for authentication:

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

    def on_start(self):
        """Authenticate once per simulated user."""
        resp = self.client.post("/api/auth/login", json={
            "email": f"user{self.user_id}@example.com",
            "password": "testpass"
        })
        data = resp.json()
        self.token = data["access_token"]
        self.refresh_token = data["refresh_token"]
        # Set default headers for all subsequent requests
        self.client.headers.update({"Authorization": f"Bearer {self.token}"})

    def on_stop(self):
        """Clean up session."""
        self.client.post("/api/auth/logout")

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

    @task
    def update_settings(self):
        self.client.put("/api/users/me/settings", json={"theme": "dark"})

Multiple User Classes

Model different user types in one test:

class AnonymousUser(HttpUser):
    weight = 3  # 75% of users
    wait_time = between(2, 5)

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

    @task
    def search(self):
        self.client.get("/search?q=python+books")

class RegisteredUser(HttpUser):
    weight = 1  # 25% of users
    wait_time = between(1, 3)

    def on_start(self):
        self.client.post("/api/login", json={
            "email": "user@example.com",
            "password": "pass"
        })

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

    @task
    def purchase(self):
        self.client.post("/api/orders", json={"item_id": 1})

Locust distributes the total user count across classes by weight: 1000 users → 750 anonymous, 250 registered.

Realistic User Data

Hard-coded requests don't reflect real load. Use random data or fixtures:

import random
from faker import Faker

fake = Faker()

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

    def on_start(self):
        # Create a unique test user
        self.email = fake.email()
        self.client.post("/api/register", json={
            "name": fake.name(),
            "email": self.email,
            "password": "TestPassword123"
        })
        self.client.post("/api/login", json={
            "email": self.email,
            "password": "TestPassword123"
        })

    @task
    def create_post(self):
        self.client.post("/api/posts", json={
            "title": fake.sentence(),
            "content": fake.paragraph(nb_sentences=5)
        })

    @task(3)
    def read_posts(self):
        page = random.randint(1, 10)
        self.client.get(f"/api/posts?page={page}")

Custom HTTP Client Configuration

Locust's HttpUser wraps the requests library. Customize it:

from locust import HttpUser
import urllib3

class ConfiguredUser(HttpUser):
    # Disable SSL verification (for staging environments)
    verify = False

    def on_start(self):
        # Set session-level headers
        self.client.headers.update({
            "Accept": "application/json",
            "X-API-Version": "2"
        })
        # Increase timeout
        self.client.timeout = 30

    @task
    def api_call(self):
        with self.client.get(
            "/api/slow-endpoint",
            timeout=60,
            catch_response=True  # Handle non-2xx manually
        ) as resp:
            if resp.status_code == 503:
                resp.failure("Service unavailable")
            elif resp.elapsed.total_seconds() > 5:
                resp.failure(f"Slow response: {resp.elapsed.total_seconds()}s")
            else:
                resp.success()

Custom Clients for Non-HTTP Protocols

Locust isn't limited to HTTP. Build custom clients for WebSockets, gRPC, or databases:

from locust import User, task, between, events
import websocket
import time

class WebSocketClient:
    def __init__(self, host, request_event):
        self.host = host
        self.request_event = request_event
        self.ws = websocket.WebSocket()

    def connect(self):
        self.ws.connect(self.host)

    def send(self, message, name="websocket"):
        start = time.time()
        try:
            self.ws.send(message)
            response = self.ws.recv()
            elapsed = (time.time() - start) * 1000
            self.request_event.fire(
                request_type="WS",
                name=name,
                response_time=elapsed,
                response_length=len(response),
                exception=None
            )
            return response
        except Exception as e:
            elapsed = (time.time() - start) * 1000
            self.request_event.fire(
                request_type="WS",
                name=name,
                response_time=elapsed,
                response_length=0,
                exception=e
            )

class WebSocketUser(User):
    wait_time = between(0.5, 1.5)

    def on_start(self):
        self.ws_client = WebSocketClient(
            "ws://localhost:8765",
            self.environment.events.request
        )
        self.ws_client.connect()

    @task
    def send_message(self):
        self.ws_client.send('{"type": "ping", "data": "test"}', name="ping")

    @task(3)
    def get_data(self):
        self.ws_client.send('{"type": "getData", "id": 1}', name="getData")

Handling Responses and Catching Failures

Use catch_response=True to validate response content, not just status codes:

@task
def create_order(self):
    payload = {"items": [{"id": 1, "qty": 2}]}

    with self.client.post(
        "/api/orders",
        json=payload,
        catch_response=True
    ) as resp:
        if resp.status_code == 201:
            data = resp.json()
            if "order_id" not in data:
                resp.failure("Response missing order_id")
            elif data.get("status") != "created":
                resp.failure(f"Unexpected status: {data.get('status')}")
            else:
                resp.success()
        elif resp.status_code == 429:
            # Rate limited — don't count as failure
            resp.success()
        else:
            resp.failure(f"Unexpected status: {resp.status_code}")

Parameterized Requests

For tests covering many different IDs or inputs, use class-level state:

import itertools

class ReadHeavyUser(HttpUser):
    wait_time = between(0.5, 2)

    # Shared across all user instances — thread-safe with itertools
    product_ids = itertools.cycle(range(1, 10001))

    @task
    def view_product(self):
        pid = next(self.product_ids)
        self.client.get(f"/api/products/{pid}", name="/api/products/[id]")

The name parameter groups requests in Locust's stats view. Without it, every unique URL appears as a separate row—your stats table becomes unreadable with 10,000 product IDs.

Summary

Locust's task model is Python code: task weights, sequential flows, custom clients, and parameterized requests are all first-class. Start with @task(weight) for proportional behavior, use on_start for authentication, add catch_response=True for business-logic validation, and build custom clients when you need to test WebSockets or gRPC. The pattern that makes Locust tests reliable: treat each simulated user as a stateful entity that authenticates once and maintains context across tasks—exactly how real users behave.

Read more

Start now free