Load-Testing a Laravel API with k6: From Smoke Test to CI Gate
Fifty users are fine and five hundred take the app down; nobody measured the stretch in between. k6 runs open-model load, fails on its own when a threshold breaks, and fits inside a continuous integration pipeline.
What k6 Measures (and What It Doesn't)
k6 runs a JavaScript script from a single binary and repeats one function per virtual user, the VUs. Only a handful of metrics matter: http_req_duration for the total request time, http_req_waiting for the time to first byte, http_req_failed for the failure rate, http_reqs for requests per second, and checks for contract assertions. Everything else is built on top of those five.
What k6 will not tell you is why. It will say the p95 hit 1.2 seconds at eighty requests per second; it will not say whether that came from the PHP-FPM pool, an unindexed query or a database out of free connections. That why comes from logs, APM and an EXPLAIN. Blurring the two layers is the fastest way to optimise blind.
Closed VUs vs. Open Arrival Rates
A closed-VU scenario, such as constant-vus or ramping-vus, fires a request, waits for the answer and starts again. When the server bogs down, the request rate drops on its own and the result looks better than reality: you end up measuring the client's patience, not the server's capacity. Open-model executors, constant-arrival-rate and ramping-arrival-rate, do the opposite: iterations start at a fixed rate regardless of response time, which is what happens when real users show up at once.
Read also
The First Script: Three Endpoints and a Contract
The minimum skeleton covers login, listing and detail, with a tag per endpoint so each one can carry its own threshold. Login belongs in setup(), which runs once per test, and the token is handed to every VU.
import http from 'k6/http';
import { check, sleep } from 'k6';
const BASE = __ENV.BASE_URL || 'https://staging.your-app.com';
export const options = {
scenarios: {
reads: {
executor: 'constant-arrival-rate',
rate: 50,
timeUnit: '1s',
duration: '2m',
preAllocatedVUs: 50,
maxVUs: 200,
},
},
thresholds: {
'http_req_duration{name:listing}': ['p(95)<400'],
'http_req_duration{name:detail}': ['p(95)<250'],
http_req_failed: ['rate<0.01'],
checks: ['rate>0.99'],
},
discardResponseBodies: true,
};
export function setup() {
const res = http.post(`${BASE}/api/login`, JSON.stringify({
email: __ENV.TEST_EMAIL,
password: __ENV.TEST_PASSWORD,
}), { headers: { 'Content-Type': 'application/json' }, tags: { name: 'login' } });
check(res, { 'login 200': (r) => r.status === 200 });
return { token: res.json('token') };
}
export default function (data) {
const headers = { Authorization: `Bearer ${data.token}` };
const listing = http.get(`${BASE}/api/posts?page=1`, { headers, tags: { name: 'listing' } });
check(listing, { 'listing 200': (r) => r.status === 200 });
const detail = http.get(`${BASE}/api/posts/1131`, { headers, tags: { name: 'detail' } });
check(detail, { 'detail 200': (r) => r.status === 200 });
sleep(0.5);
}
export function handleSummary(data) {
return { 'summary.json': JSON.stringify(data) };
}Every piece earns its place. tags.name is what makes per-endpoint thresholds possible; without a tag, a slow listing and a fast detail get averaged, and the threshold tells you nothing. discardResponseBodies keeps each response body out of VU memory, which at medium load weighs more than it looks. And sleep() under an open arrival rate does not slow the arrival rate: it burns one VU's time and may force you to raise maxVUs.
Test Data Without Dirtying the Database
setup() runs once per test and teardown() once at the end: that is where the test user, the IDs you will query and the cleanup belong. What must never happen is creating a record per iteration, because at fifty per second for two minutes you have turned a read-load test into a write load test and the numbers no longer describe your API.
Scenarios: One Script, Four Ways to Load
You do not need a script per test type. The smoke test is a minute with one to five VUs: proof that the script works and the environment answers. Sustained load is the main run, at a constant arrival rate. A ramp raises the rate in steps toward the target, and that is where you see latency break away. Spike and soak runs, with heavy load for half an hour or more, expose memory leaks and connections that never close.
Under open arrivals you must size preAllocatedVUs, reserved from the start, and maxVUs, the ceiling it can climb to. When the server slows down, each iteration lasts longer and more VUs are needed to hold the rate. Once they run out, k6 reports Insufficient VUs: that is not a script bug, it is the scenario asking for more muscle than you reserved.
Thresholds: the Test Fails on Its Own
A threshold is an expression over a metric, evaluated at the end, and it turns the test from a report into a contract. Four forms cover most needs: p(95)<400 for percentiles, rate<0.01 for rates, count>=500 for volume and rate>0.99 for the share of passing checks. Put several expressions in an array and all of them are evaluated, so one failing is enough.
To stop early instead of burning two minutes, abortOnFail with delayAbortEval aborts after a grace period, so a cold start does not kill the run. Two details that cost people real time: check() does not fail the test by itself, it only feeds the checks metric, and http_req_failed counts any 4xx and any 5xx as a failure by default. On an API with throttle: or an expected 401, the gate goes red by design until you separate that case with http.setResponseCallback() or with per-tag thresholds.
Measuring the Right Server: Laravel's Traps
The most common trap is testing against php artisan serve. That command uses PHP's built-in server, one process by default, so you are measuring the development server rather than your application. The test belongs on the real runtime: PHP-FPM behind nginx, or the Octane server with production worker counts and max-requests.
The second trap is lukewarm configuration: APP_DEBUG=true adds work to every request, and without php artisan config:cache or route:cache the bootstrap pays what production never pays. On Octane the worker lives in memory, and opcache.enable_cli=1 changes the result. The third is the queue: with QUEUE_CONNECTION=sync the job runs inside the request, so you are timing the queue, not the response.
Three more details ruin measurements. throttle: returns 429 and that counts as a failure. Cookies: k6 keeps one jar per VU, so in session flows clear it between iterations or use a token. And page cache: the first pass measures the database and the second measures the cache, so run and report both, saying which is which. If the FPM pool is small or the database runs out of connections, you get 502 and 504 errors that look like a slow application.
The CI Gate and What the Test Can't Tell You
A sane gate has two speeds. Every pull request runs a short smoke test that only proves the script starts and the endpoints answer. The full load run happens at night or on a fixed machine, because a strict latency threshold on a shared runner produces false reds. k6 exits with code 99 when a threshold fails and 0 when everything passes, so the pipeline step goes red without parsing logs; handleSummary() saves the summary as an artifact and k6 run --out json=results.json keeps the full series.
What the test cannot tell you is the cause. A high p95 may come from an unindexed query, an N+1 or a badly sized pool, and none of that is in the summary. Cross the result with the server logs during the run, the FPM pool state and the slow query log. If the bottleneck is at bootstrap, the work on Octane and application servers is the next step; if it shows up on the first pass and vanishes on the second, look at page caching and TTFB. And if what you want to measure is the experience in the browser, that is another layer: Core Web Vitals and browser testing with Pest.
A twenty-line script, three scenarios and four thresholds are enough to stop guessing. The rest is rerunning the test whenever you change something that can affect performance, and comparing against the previous number instead of against a feeling.

