id: locust-load-test-slo-gate
namespace: company.team
description: |
Run a headless Locust load test against a staging API after each deploy,
keep the per-endpoint statistics, and fail the execution when the p95
latency or the failure rate breaks the service-level objective, so a
release flow can wait on it.
inputs:
- id: host
type: STRING
defaults: "https://staging.example.com"
displayName: "Target Host"
description: "Base URL of the API under test. Point it at staging or a preview
environment, never at production."
- id: paths
type: STRING
defaults: "/health,/api/items"
displayName: "Endpoints (GET, comma-separated)"
description: "GET paths every simulated user calls in turn, for example
`/health,/api/items`."
- id: extra_header
type: STRING
defaults: "X-Request-Source: kestra-locust"
displayName: "Extra Request Header"
description: "One `Name: value` header sent with every request, for example a
tenant or routing header."
- id: users
type: INT
defaults: 20
displayName: "Concurrent Users"
description: "Peak number of simulated users."
- id: spawn_rate
type: INT
defaults: 5
displayName: "Spawn Rate (users/s)"
description: "How many users start per second until the peak is reached."
- id: run_time
type: STRING
defaults: "60s"
displayName: "Run Time"
description: "Test duration in Locust syntax, for example `60s`, `5m`."
- id: p95_limit_ms
type: INT
defaults: 500
displayName: "p95 Latency Limit (ms)"
description: "The run fails when the aggregated 95th percentile response time is
above this."
- id: max_failure_pct
type: FLOAT
defaults: 1.0
displayName: "Max Failure Rate (%)"
description: "The run fails when more than this share of requests failed (HTTP
errors, timeouts, connection errors)."
triggers:
- id: after_staging_deploy
type: io.kestra.plugin.core.trigger.Flow
description: Run the load test every time the staging deploy flow succeeds.
Shipped disabled; point it at your own deploy flow and enable it after a
manual run.
disabled: true
dependsOn:
- namespace: company.team
flowId: deploy_staging
states: [ SUCCESS ]
tasks:
- id: load_test
type: io.kestra.plugin.scripts.python.Commands
description: Install a pinned Locust, write a small locustfile that calls the
configured GET paths with the extra header, and run it headless with CSV
output. Locust exits non-zero when any request fails, so the exit code is
recorded instead of failing the task and the statistics are always kept.
containerImage: python:3.12-slim
env:
TARGET_PATHS: "{{ inputs.paths }}"
EXTRA_HEADER: "{{ inputs.extra_header }}"
inputFiles:
locustfile.py: |
import os
from locust import HttpUser, between, task
PATHS = [p.strip() for p in os.environ.get("TARGET_PATHS", "/").split(",") if p.strip()]
HEADER = os.environ.get("EXTRA_HEADER", "")
class ApiUser(HttpUser):
wait_time = between(0.5, 1.5)
def on_start(self):
if ":" in HEADER:
name, value = HEADER.split(":", 1)
self.client.headers[name.strip()] = value.strip()
@task
def get_paths(self):
for path in PATHS:
self.client.get(path, name=path)
beforeCommands:
- pip install --quiet --disable-pip-version-check locust==2.46.7
commands:
- >-
rc=0; locust -f locustfile.py --headless --users {{ inputs.users }}
--spawn-rate {{ inputs.spawn_rate }} --run-time {{ inputs.run_time }}
--host '{{ inputs.host }}' --csv run --only-summary || rc=$?; echo $rc >
exit_code.txt; echo locust exit code $rc
outputFiles:
- run_stats.csv
- run_failures.csv
- exit_code.txt
timeout: PT30M
- id: evaluate_slo
type: io.kestra.plugin.scripts.python.Script
description: Read Locust's statistics CSV, take the Aggregated row for request
count, failures, requests per second and p95, list each endpoint with its
own p95 and failures, and decide whether the run breaks the SLO. No
statistics, or zero requests, counts as a breach.
containerImage: python:3.12-slim
inputFiles:
run_stats.csv: "{{ outputs.load_test.outputFiles['run_stats.csv'] ?? '' }}"
run_failures.csv: "{{ outputs.load_test.outputFiles['run_failures.csv'] ?? '' }}"
script: |
import csv, json, os
p95_limit = {{ inputs.p95_limit_ms }}
max_failure_pct = {{ inputs.max_failure_pct }}
def num(value):
try:
return float(value)
except (TypeError, ValueError):
return None
result = {"verdict": "NO_DATA", "breached": True, "requests": 0, "failures": 0,
"failure_pct": 0, "p95_ms": None, "rps": 0, "endpoints": [], "errors": [],
"reasons": ["Locust produced no statistics; check the load_test logs."]}
if os.path.exists("run_stats.csv") and os.path.getsize("run_stats.csv") > 0:
rows = list(csv.DictReader(open("run_stats.csv", encoding="utf-8")))
agg = next((r for r in rows if r["Name"] == "Aggregated"), None)
requests = int(agg["Request Count"]) if agg else 0
failures = int(agg["Failure Count"]) if agg else 0
failure_pct = round(100 * failures / requests, 2) if requests else 0
p95 = num(agg["95%"]) if agg else None
reasons = []
if requests == 0:
reasons.append("no request was completed")
if p95 is not None and p95 > p95_limit:
reasons.append(f"p95 {p95:.0f} ms is above the {p95_limit} ms limit")
if failure_pct > max_failure_pct:
reasons.append(f"failure rate {failure_pct}% is above the {max_failure_pct}% limit")
errors = []
if os.path.exists("run_failures.csv") and os.path.getsize("run_failures.csv") > 0:
errors = [f"{r['Method']} {r['Name']}: {r['Error'][:160]} x{r['Occurrences']}"
for r in csv.DictReader(open("run_failures.csv", encoding="utf-8"))]
result = {"verdict": "BREACHED" if reasons else "PASSED", "breached": bool(reasons),
"requests": requests, "failures": failures, "failure_pct": failure_pct,
"p95_ms": p95, "rps": round(num(agg["Requests/s"]) or 0, 1) if agg else 0,
"endpoints": [f"{r['Type']} {r['Name']}: {r['Request Count']} req, {r['Failure Count']} failed, p95 {r['95%']} ms"
for r in rows if r["Name"] != "Aggregated"],
"errors": errors, "reasons": reasons or ["within the SLO"]}
print("::" + json.dumps({"outputs": result}) + "::")
- id: log_results
type: io.kestra.plugin.core.log.Log
description: Log the verdict, the aggregated numbers, one line per endpoint and
one line per error type, whatever the verdict.
message: |
Locust SLO gate for {{ inputs.host }}: {{ outputs.evaluate_slo.vars.verdict }} ({{ outputs.evaluate_slo.vars.reasons | join('; ') }})
requests={{ outputs.evaluate_slo.vars.requests }} failures={{ outputs.evaluate_slo.vars.failures }} ({{ outputs.evaluate_slo.vars.failure_pct }}%) p95={{ outputs.evaluate_slo.vars.p95_ms }} ms rps={{ outputs.evaluate_slo.vars.rps }} users={{ inputs.users }} run_time={{ inputs.run_time }}
{% for line in outputs.evaluate_slo.vars.endpoints %}- {{ line }}
{% endfor %}{% for line in outputs.evaluate_slo.vars.errors %}! {{ line }}
{% endfor %}
- id: gate
type: io.kestra.plugin.core.flow.If
description: Fail the execution when the SLO is breached (or no statistics
exist), so a parent or downstream release flow stops; otherwise end green.
condition: "{{ outputs.evaluate_slo.vars.breached }}"
then:
- id: block_release
type: io.kestra.plugin.core.execution.Fail
description: Stop here with the reasons; the statistics CSVs stay attached to
the execution.
errorMessage: "Load test SLO BREACHED for {{ inputs.host }}: {{
outputs.evaluate_slo.vars.reasons | join('; ') }}. See log_results and
the run_stats.csv output."
else:
- id: log_passed
type: io.kestra.plugin.core.log.Log
message: "Load test SLO met for {{ inputs.host }}: p95 {{
outputs.evaluate_slo.vars.p95_ms }} ms, {{
outputs.evaluate_slo.vars.failure_pct }}% failed."
outputs:
- id: verdict
type: STRING
value: "{{ outputs.evaluate_slo.vars.verdict ?? 'NO_DATA' }}"