Locust CI/CD Integration: Automated Performance Testing in Pipelines
Locust runs headlessly with --headless, exits with code 1 if performance thresholds fail, and integrates into any CI pipeline. This guide covers GitHub Actions, GitLab CI, and Jenkins workflows, environment-specific configurations, threshold enforcement, and artifact upload for test reports.
Performance testing in CI prevents regressions before they reach production. Without it, a new database query or a missing cache index can double response times and nobody notices until users complain. Locust's headless mode and exit code control make it a first-class CI citizen.
Headless Mode Basics
Locust's --headless flag disables the web UI and runs the test programmatically:
locust \
--headless \
--users 200 \
--spawn-rate 20 \
--run-time 3m \
--host https://staging.example.com \
--locustfile tests/load/locustfile.pyLocust exits with code 0 on success, 1 if the process crashed. For performance-based pass/fail, you need custom exit code logic (covered below).
Project Structure
Organize load tests alongside your application code:
your-repo/
├── src/
├── tests/
│ ├── unit/
│ ├── integration/
│ └── load/
│ ├── locustfile.py
│ ├── requirements.txt
│ └── thresholds.py
├── .github/workflows/
│ └── performance.yml
└── ...Keep load tests in version control with the application. When a PR changes an API, the author can run load tests locally before pushing.
Threshold Enforcement
Add a threshold check to your locustfile:
# tests/load/locustfile.py
from locust import HttpUser, task, between, events
class APIUser(HttpUser):
wait_time = between(0.5, 2)
@task(3)
def list_items(self):
self.client.get("/api/items")
@task(1)
def create_item(self):
self.client.post("/api/items", json={
"name": "Test Item",
"value": 42
})
# Thresholds checked at test end
THRESHOLDS = {
"max_failure_rate": 0.01, # < 1% failures
"max_p95_ms": 500, # p95 under 500ms
"min_rps": 50, # at least 50 RPS
}
@events.quitting.add_listener
def check_thresholds(environment, **kw):
stats = environment.runner.stats.total
failed = False
failure_rate = stats.fail_ratio
if failure_rate > THRESHOLDS["max_failure_rate"]:
print(f"THRESHOLD FAIL: failure rate {failure_rate:.1%} > {THRESHOLDS['max_failure_rate']:.1%}")
failed = True
p95 = stats.get_response_time_percentile(0.95)
if p95 > THRESHOLDS["max_p95_ms"]:
print(f"THRESHOLD FAIL: p95 {p95:.0f}ms > {THRESHOLDS['max_p95_ms']}ms")
failed = True
rps = stats.current_rps
if rps < THRESHOLDS["min_rps"]:
print(f"THRESHOLD FAIL: RPS {rps:.1f} < {THRESHOLDS['min_rps']}")
failed = True
if not failed:
print(f"All thresholds passed: p95={p95:.0f}ms, RPS={rps:.1f}, failures={failure_rate:.1%}")
else:
environment.process_exit_code = 1GitHub Actions Integration
On-demand Performance Test
# .github/workflows/performance.yml
name: Performance Tests
on:
workflow_dispatch:
inputs:
users:
description: 'Number of concurrent users'
default: '200'
duration:
description: 'Test duration (e.g. 3m, 10m)'
default: '3m'
pull_request:
paths:
- 'src/api/**' # Only run when API code changes
jobs:
load-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Install dependencies
run: pip install -r tests/load/requirements.txt
- name: Run load test
env:
TARGET_HOST: ${{ secrets.STAGING_URL }}
run: |
locust \
--headless \
--users ${{ github.event.inputs.users || 200 }} \
--spawn-rate 20 \
--run-time ${{ github.event.inputs.duration || '3m' }} \
--host $TARGET_HOST \
--locustfile tests/load/locustfile.py \
--csv reports/locust
- name: Upload test reports
if: always() # Upload even on failure
uses: actions/upload-artifact@v4
with:
name: locust-results
path: reports/
retention-days: 30PR Performance Gate
Run a shorter, lighter test on every PR that touches API code:
name: PR Performance Gate
on:
pull_request:
paths:
- 'src/**'
jobs:
smoke-perf:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Start application
run: |
docker compose up -d app db
# Wait for app to be healthy
timeout 60 bash -c 'until curl -f http://localhost:8080/health; do sleep 2; done'
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Install Locust
run: pip install locust
- name: Run smoke load test
run: |
locust \
--headless \
--users 50 \
--spawn-rate 10 \
--run-time 1m \
--host http://localhost:8080 \
--locustfile tests/load/locustfile.py \
--csv reports/pr-smoke
- name: Comment results on PR
if: always()
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const csv = fs.readFileSync('reports/pr-smoke_stats.csv', 'utf8');
const lines = csv.split('\n').slice(0, 5);
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: `## Load Test Results\n\`\`\`\n${lines.join('\n')}\n\`\`\``
});GitLab CI Integration
# .gitlab-ci.yml
stages:
- build
- test
- performance
performance-test:
stage: performance
image: python:3.11-slim
variables:
TARGET_HOST: $STAGING_URL
before_script:
- pip install locust
script:
- |
locust \
--headless \
--users 200 \
--spawn-rate 25 \
--run-time 5m \
--host $TARGET_HOST \
--locustfile tests/load/locustfile.py \
--csv reports/locust-$CI_COMMIT_SHORT_SHA
artifacts:
when: always
paths:
- reports/
expire_in: 7 days
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
when: manual # Manual for MRs, automatic on main
- if: $CI_COMMIT_BRANCH == "main"
when: alwaysJenkins Pipeline
// Jenkinsfile
pipeline {
agent any
parameters {
string(name: 'TARGET_HOST', defaultValue: 'https://staging.example.com')
string(name: 'USERS', defaultValue: '200')
string(name: 'DURATION', defaultValue: '5m')
}
stages {
stage('Load Test') {
steps {
sh '''
pip install locust --quiet
mkdir -p reports
locust \
--headless \
--users ${USERS} \
--spawn-rate 25 \
--run-time ${DURATION} \
--host ${TARGET_HOST} \
--locustfile tests/load/locustfile.py \
--csv reports/locust \
--html reports/locust-report.html
'''
}
}
}
post {
always {
archiveArtifacts artifacts: 'reports/**', allowEmptyArchive: true
publishHTML(target: [
allowMissing: false,
alwaysLinkToLastBuild: true,
reportDir: 'reports',
reportFiles: 'locust-report.html',
reportName: 'Locust Performance Report'
])
}
failure {
slackSend(
color: 'danger',
message: "Performance test failed for ${env.JOB_NAME} #${env.BUILD_NUMBER}"
)
}
}
}Environment Configuration
Avoid hardcoding environment details in locustfiles. Use environment variables:
# locustfile.py
import os
from locust import HttpUser, task, between
# Environment-specific thresholds
ENV = os.getenv("TEST_ENV", "staging")
THRESHOLDS = {
"staging": {"max_p95_ms": 500, "max_failure_rate": 0.01},
"production": {"max_p95_ms": 200, "max_failure_rate": 0.001},
}[ENV]
class APIUser(HttpUser):
wait_time = between(
float(os.getenv("MIN_WAIT", "0.5")),
float(os.getenv("MAX_WAIT", "2"))
)
@task
def api_call(self):
self.client.get("/api/items")Configure per-environment in CI:
# Staging
TEST_ENV=staging locust --headless --users 200 --run-time 5m ...
# Production (lighter, tighter thresholds)
TEST_ENV=production locust --headless --users 50 --run-time 2m ...Docker-Based CI Tests
Run Locust and your app together in Docker for isolated, reproducible tests:
# docker-compose.ci.yml
version: '3.8'
services:
app:
build: .
environment:
- DATABASE_URL=postgresql://postgres:postgres@db/testdb
depends_on:
db:
condition: service_healthy
db:
image: postgres:15
environment:
POSTGRES_PASSWORD: postgres
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
locust:
image: locustio/locust
volumes:
- ./tests/load:/mnt/locust
command: >
--headless
--users 100
--spawn-rate 10
--run-time 3m
--host http://app:8080
--locustfile /mnt/locust/locustfile.py
--csv /mnt/locust/reports/results
depends_on:
- app# In CI
docker compose -f docker-compose.ci.yml up --exit-code-from locustThe --exit-code-from locust flag makes Docker Compose exit with Locust's exit code, propagating test failures to your CI system.
HTML Report Generation
Locust generates a standalone HTML report with --html:
locust \
--headless \
--users 200 \
--spawn-rate 20 \
--run-time 5m \
--host https://staging.example.com \
--csv reports/results \
--html reports/report.htmlThe HTML report includes charts, stats tables, and failure details in a single self-contained file—easy to attach to GitHub Actions artifacts, send via Slack, or archive in Jenkins.
Scheduled Performance Tests
Run performance tests on a schedule to catch gradual degradation:
# .github/workflows/nightly-perf.yml
name: Nightly Performance Baseline
on:
schedule:
- cron: '0 2 * * *' # 2am UTC daily
jobs:
baseline:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run baseline test
run: |
pip install locust
locust \
--headless \
--users 500 \
--spawn-rate 50 \
--run-time 15m \
--host ${{ secrets.PRODUCTION_URL }} \
--csv reports/nightly-$(date +%Y-%m-%d) \
--html reports/nightly-$(date +%Y-%m-%d).html
- name: Archive results
uses: actions/upload-artifact@v4
with:
name: nightly-perf-$(date +%Y-%m-%d)
path: reports/Compare nightly CSV results to detect week-over-week trends.
Summary
Locust integrates into any CI pipeline through --headless mode and exit codes. The pattern that works: run a lightweight smoke test on every PR, a full baseline on merges to main, and a long-duration stress test nightly. Enforce SLOs via the quitting event listener, upload HTML reports as artifacts, and route failures to Slack. Performance testing stops being a quarterly ritual and becomes a continuous signal—the same way you think about unit test coverage.