🦗 Locust · 레슨 2 / 6

Locust 사용자 행동 작성 — task 가중치, 대기 시간, TaskSet, 여러 사용자 유형

task 가중치로 행동 비율 정하기, between·constant_pacing·constant_throughput 대기 시간의 차이, on_start/on_stop, 순서가 있는 흐름을 SequentialTaskSet으로 표현하기, 여러 사용자 유형과 비율, 태그로 일부 task만 실행하기, FastHttpUser를 배웁니다.

⏱ 약 5분🗓 2026-11-11 업데이트🏷 Locust 2.x 기준

이 레슨에서 배우는 것

  • task 가중치와 대기 시간으로 현실적인 행동 비율 만들기
  • 순서가 있는 사용자 흐름 표현하기
  • 여러 사용자 유형을 비율대로 섞기

task 가중치

@task(가중치)로 각 행동이 선택될 확률을 정합니다. 아래 사용자는 메인 페이지를 3, 추천 요청을 1의 비율로 실행합니다.

locustfile.pypython
from locust import HttpUser, task, between

HEADERS = {"Authorization": "token abcdef0123456789"}  # QuickPizza 데모용 고정 토큰


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

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

    @task(1)
    def recommend(self):
        self.client.post(
            "/api/pizza",
            json={"maxCaloriesPerSlice": 700, "mustBeVegetarian": False},
            headers=HEADERS,
            name="POST /api/pizza",   # 통계에 표시될 이름
        )

운영 로그에서 "조회 70%, 검색 20%, 주문 10%"처럼 비율을 구했다면 그대로 가중치 7:2:1로 옮기면 됩니다.

대기 시간 함수

함수동작쓰임새
between(a, b)task 사이에 a~b초 무작위 대기사람의 think time (가장 흔함)
constant(n)항상 n초 대기단순 반복
constant_pacing(n)task 시작 간격을 n초로 맞춤 (task가 오래 걸리면 덜 쉼)사용자당 주기 고정
constant_throughput(r)사용자당 초당 최대 r회 task 실행목표 처리량 맞추기

Locust는 기본적으로 사용자 수를 정하는 닫힌 모델입니다. 서버가 느려지면 사용자들이 응답을 기다리느라 처리량이 자연히 줄어듭니다. "초당 200건"처럼 처리량이 목표라면 constant_throughput을 써서 계산합니다.

text
목표 200 RPS, 사용자당 constant_throughput(2) → 사용자 100명 필요
단, 응답 시간이 0.5초를 넘으면 사용자당 2회/초를 채우지 못해 목표 미달 → 사용자를 넉넉히

on_start / on_stop

사용자 인스턴스가 시작될 때 한 번(로그인), 멈출 때 한 번(로그아웃) 실행할 코드를 둡니다.

python
class MemberUser(HttpUser):
    wait_time = between(1, 3)

    def on_start(self):
        res = self.client.post("/auth/login", json={"username": "user01", "password": "pass-01"})
        self.client.headers["Authorization"] = f"Bearer {res.json()['accessToken']}"

    def on_stop(self):
        self.client.post("/auth/logout")

    @task
    def my_orders(self):
        self.client.get("/me/orders")

self.client.headers에 넣은 값은 이 사용자의 이후 모든 요청에 붙습니다. 쿠키도 사용자별 세션에 자동 저장됩니다.

순서가 있는 흐름 — SequentialTaskSet

"상품 목록 → 상세 → 장바구니 → 주문"처럼 순서가 중요한 흐름은 SequentialTaskSet으로 묶습니다. task가 선언 순서대로 실행되고 끝나면 처음부터 반복합니다.

python
from locust import HttpUser, SequentialTaskSet, task, between


class CheckoutFlow(SequentialTaskSet):
    @task
    def list_products(self):
        res = self.client.get("/products")
        self.product_id = res.json()["items"][0]["id"]   # 다음 task에서 사용

    @task
    def product_detail(self):
        self.client.get(f"/products/{self.product_id}", name="/products/[id]")

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

    @task
    def checkout(self):
        self.client.post("/orders")
        self.interrupt()   # 흐름 종료 → 부모 사용자로 돌아감 (다음 반복은 처음부터)


class Shopper(HttpUser):
    wait_time = between(1, 2)
    tasks = [CheckoutFlow]
💡
name 인자로 URL 묶기

/products/1, /products/2…를 그대로 두면 통계에 URL마다 행이 생깁니다. name="/products/[id]"로 묶어야 결과를 읽을 수 있습니다.

여러 사용자 유형

locustfile에 HttpUser 클래스가 여러 개 있으면 모두 실행됩니다. 클래스의 weight로 인원 비율을, fixed_count로 고정 인원을 정합니다.

python
class Visitor(HttpUser):
    weight = 8                       # 전체 사용자의 80%
    wait_time = between(2, 5)

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


class Buyer(HttpUser):
    weight = 2                       # 20%
    wait_time = between(1, 3)

    @task
    def order(self):
        self.client.post("/api/pizza", json={}, headers=HEADERS, name="POST /api/pizza")


class Admin(HttpUser):
    fixed_count = 1                  # 사용자 수와 관계없이 딱 1명
    wait_time = between(10, 20)

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

실행 시 특정 클래스만 고를 수도 있습니다: locust Visitor Buyer.

태그로 일부만 실행

python
from locust import tag

class PizzaUser(HttpUser):
    @tag("smoke")
    @task
    def home(self):
        self.client.get("/")

    @tag("heavy")
    @task
    def report(self):
        self.client.get("/api/report")
bash
locust --tags smoke          # smoke 태그 task만
locust --exclude-tags heavy  # heavy 제외

FastHttpUser

기본 HttpUser는 사용하기 편한 requests 라이브러리 기반이지만 CPU를 많이 씁니다. 부하 생성기 CPU가 먼저 바닥난다면 FastHttpUser로 바꿔 보세요. 더 빠른 HTTP 클라이언트(geventhttpclient)를 써서 같은 머신에서 몇 배의 요청을 만들 수 있습니다. 사용법은 대부분 같지만 일부 인자(requests 전용 옵션)는 다르니 문서를 확인하세요.

python
from locust import FastHttpUser, task

class FastUser(FastHttpUser):
    @task
    def home(self):
        self.client.get("/")

정리