k6 workload models
You can choose a closed virtual-user workload for browsing and an open arrival-rate workload for orders to generate the traffic patterns you need to measure.
Learning outcomes
- Explain how a k6 load test measures throughput, concurrency, latency and errors against the restaurant and order APIs.
- Distinguish closed virtual-user workloads from open arrival-rate workloads and choose the right model for each API.
- Interpret p95 and p99 latency, configure thresholds and distinguish response checks from aggregate performance requirements.
- Produce reproducible before numbers that can be compared with after numbers when investigating a bottleneck.
Hundreds of customers may browse restaurants or place orders at the same time. Your API can return correct responses during manual testing and still struggle when that traffic arrives continuously. You need to generate controlled traffic, measure the response distribution and preserve the results before changing the implementation.
The restaurant list and menu endpoints represent read traffic. Order creation represents write traffic because it authenticates a customer, writes an order to MySQL and publishes an event through the outbox. These workloads behave differently under pressure, so you should not measure them with the same traffic model.
Load-test measurements
A Load test sends controlled traffic to a running service and records how the service responds. It helps you identify performance limits before real customers encounter them.
The Week 6 backend exposes three important endpoints:
GET /v1/restaurants
GET /v1/restaurants/{id}/menu
POST /v1/ordersThe restaurant list involves database reads. Menu retrieval can benefit from the Redis menu cache. Order creation involves authentication, database transactions and the outbox.
A useful load test records several measurements.
Throughput measures how much work the service completes over time. For HTTP traffic, you usually express it as requests per second (RPS).
Latency measures how long a request takes from the load generator's perspective. A request that takes 40 milliseconds completes faster than one that takes 800 milliseconds.
Error rate measures the proportion of requests that fail. A low latency result means little when many requests are rejected or return errors.
Concurrency measures how many operations are in progress at the same time.
Consider a backend that receives 100 requests per second. It might respond quickly to most requests but experience a growing number of timeouts as its database connection pool becomes saturated. Throughput, latency and errors reveal different parts of that failure.
You need all these measurements to understand what the system can sustain.
k6 scripts
k6 executes JavaScript scripts that generate HTTP traffic. Your Go backend does not need a k6 dependency. You install the k6 command-line tool on the machine running the load test.
A script exports an options object that describes the workload and its performance requirements. The default function defines the work performed by each iteration.
A small browsing example looks like this:
import http from 'k6/http';
import { check, sleep } from 'k6';
const BASE_URL = __ENV.BASE_URL || 'http://localhost:8080';
export const options = {
vus: 10,
duration: '2m',
};
export default function () {
const response = http.get(`${BASE_URL}/v1/restaurants`);
check(response, {
'restaurant list returns 200': r => r.status === 200,
});
sleep(1);
}The BASE_URL environment variable lets you run the same script against different environments without changing its source. The example uses ten VUs for two minutes. These values illustrate the configuration, not the workload required by the exercise.
The check() function evaluates an individual response. Here, it verifies that the restaurant endpoint returns HTTP 200.
The script's options object is evaluated when k6 loads the file. This matters when configuration comes from __ENV. Compute environment-dependent values at load time rather than expecting the workload to change its options while running.
You can inspect the exported options before starting a test:
k6 inspect loadtest/browse.jsThis helps catch incorrect defaults and workload configuration without sending traffic to the API.
Virtual users and closed workloads
A virtual user (VU) represents one simulated client executing the default function in a loop.
With ten VUs, k6 creates ten independent clients. Each client finishes its current iteration before starting another one.
export const options = {
vus: 10,
duration: '2m',
};This is a closed workload model. The number of active clients stays fixed during the configured duration.
The request rate depends on how long each iteration takes. Consider ten VUs completing iterations that each take one second. They can generate approximately ten iterations per second.
Now suppose each iteration takes two seconds:
VUs: 10
Iteration duration: 2 seconds
Approximate rate: 5 iterations/secondThe request rate decreases because each VU waits for its previous iteration to finish.
This distinction matters when you measure browsing traffic. A fixed number of active customers repeatedly requesting restaurant data represents a reasonable closed workload.
The browse script in the exercise defaults to 300 VUs for three minutes. Each iteration requests the restaurant list and then a restaurant menu.
The VU count represents concurrent simulated clients, not requests per second. The actual request rate depends on response times and the work performed inside each iteration.
Identity and rate limiting
Your API already has per-identity rate limiting. It uses the X-User-ID header when present and falls back to the client address when the header is absent.
The HTTP identity key lets the load generator represent separate clients.
For example, a browsing VU can use its VU number as part of its identity:
const headers = {
'X-User-ID': `browse-${__VU}`,
};
const response = http.get(
`${BASE_URL}/v1/restaurants`,
{ headers }
);The __VU value identifies the current virtual user. Each VU therefore sends requests under its own identity.
Without this header, multiple VUs running on one machine may share the same client address. The rate limiter can then treat them as one caller.
This creates a misleading result. You might believe the restaurant API cannot handle the intended workload when the real problem is that the load generator is sharing one rate-limit bucket.
Keep this identity mechanism restricted to your local test environment or a trusted test proxy. Public clients must not be allowed to choose arbitrary user identities.
Gradual traffic with load stages
A load test should increase traffic in a controlled way rather than immediately starting at its maximum target.
Load stages describe how a workload changes over time. A stage specifies a duration and a target. For a VU-based workload, the target represents the number of active VUs.
Consider this illustrative configuration:
export const options = {
stages: [
{ duration: '30s', target: 10 },
{ duration: '1m', target: 30 },
{ duration: '1m', target: 50 },
{ duration: '30s', target: 0 },
],
};The workload starts with ten VUs, increases to thirty, reaches fifty and then decreases to zero.
Gradual increases help you observe when latency starts rising or errors appear. They also allow database connections and caches to warm up before the workload reaches its highest level.
A sudden increase can reveal that the service struggles, but it gives you less information about the point where performance begins to degrade.
Load stages can also support a warm-up period. Your first restaurant requests might establish database connections or populate the menu cache. Those requests can behave differently from later requests.
Closed and open workload models
A closed workload controls concurrency. An open workload controls the arrival rate.
The distinction matters when you test order creation.
Closed workload
A fixed number of VUs repeatedly execute iterations. If the API slows down, those VUs spend more time waiting and the overall arrival rate falls.
Open workload
k6 schedules iterations at a specified arrival rate, independently of how long previous iterations take. The ramping-arrival-rate executor implements this model.
Suppose the order API must receive 100 order attempts per second. A closed workload with 100 VUs does not guarantee that rate.
If an order iteration takes two seconds, 100 VUs may generate substantially fewer than 100 iterations per second.
An open workload lets you target 100 iterations per second even as response times increase, provided the load generator has enough available VUs and resources.
The order script in the exercise uses this open model. Its default workload ramps to 100 orders per second and holds that rate. The ramp and hold durations total two minutes.
Arrival rate and concurrency
Little's Law connects arrival rate, average time in the system and average concurrency.
The formula is:
L = λ × WWhere:
Lis the average number of operations in progress.λis the arrival rate in operations per second.Wis the average time an operation takes in seconds.
Suppose the API receives 100 orders per second and each order takes 0.2 seconds on average.
L = 100 × 0.2
L = 20You need approximately 20 concurrent operations on average under these assumptions.
Actual tests need additional VUs because requests do not all take the same amount of time. Some requests take longer, and the load generator also needs enough workers to schedule new iterations.
Peak traffic
Average traffic does not describe the highest demand your service receives.
A peak factor represents the relationship between peak demand and average demand:
peak factor = peak traffic / average trafficFor example, restaurant ordering activity may increase around meal times. Capacity planning must account for those periods instead of assuming that average traffic is sufficient.
This is why the order workload targets a configured peak arrival rate. You are measuring how the API behaves under a sustained incoming workload, not merely how quickly it handles a few requests.
Order creation and idempotency
Order creation needs more preparation than restaurant browsing. The API requires an authenticated customer and a valid order body.
The order workload uses setup() to create a customer and discover a restaurant with a usable menu item. k6 executes setup once before the VU iterations begin and passes its returned data to the default function.
This keeps account creation and menu discovery outside the measured order iterations.
Every order request must include a fresh idempotency key. Your backend uses this key to prevent duplicate orders when a client retries a submission.
Suppose a client submits an order with:
Idempotency-Key: order-123The backend processes the request and records the result. When the same client submits the same key again, the backend can return the previously recorded result instead of creating another order.
This behaviour protects real customers from duplicate orders. However, it creates a problem for load testing if every iteration reuses the same key.
The first iteration might create an order with HTTP 201. Later iterations might receive HTTP 200 because the backend is returning the existing result.
Those later requests do not measure new order creation.
Generate a distinct key for every iteration. The key must remain within the API's 36-character limit.
HTTP status codes and response checks
HTTP status codes help distinguish successful reads from newly created resources.
For this workload:
| Request | Expected status |
|---|---|
| Restaurant list | 200 |
| Restaurant menu | 200 |
| New order creation | 201 |
HTTP 200 indicates a successful request. HTTP 201 indicates that the server created a resource.
That difference matters when testing the order endpoint. A repeated idempotency key may produce HTTP 200 even though you expected a new order.
A k6 check should verify the exact status:
check(response, {
'order creation returns 201': r => r.status === 201,
});Do not accept HTTP 200 as an alternative for this check. That would allow a deduplication response to pass as a newly created order.
The order request also needs the bearer token, JSON content type and valid order body. A request that returns HTTP 401, 403 or 400 is not measuring the intended successful order workload.
Latency percentiles
An average can hide the slowest requests in your system.
The k6 summary reports several statistics for http_req_duration:
| Statistic | Meaning |
|---|---|
avg | Average request duration |
med | Median request duration, also called p50 |
p(90) | Latency below which approximately 90% of requests fall |
p(95) | Latency below which approximately 95% of requests fall |
p(99) | Latency below which approximately 99% of requests fall |
A latency percentile describes the position of a request's latency within the measured distribution.
Consider these results:
Average latency: 85 ms
Median latency: 60 ms
p90: 110 ms
p95: 180 ms
p99: 750 msMost requests are fast, but the slowest portion of the distribution takes considerably longer.
The average latency of 85 milliseconds does not communicate this problem clearly. A small number of slow requests can be hidden by the large number of fast requests.
p95 tells you where the slowest five percent begin. p99 tells you where the slowest one percent begin.
This matters for restaurant browsing and order placement. A customer may experience one of the slow requests even when the average looks acceptable.
Percentiles are estimates based on the collected observations. Their precision depends on sample size. A test with only a few dozen requests cannot provide a reliable picture of p99 latency.
Collect enough requests to make the tail meaningful. When comparing before numbers and after numbers, use the same workload and compare the same percentile.
Thresholds and checks
A k6 threshold defines a pass or fail condition over a measured metric.
For example, you can require the p99 request duration to remain below 300 milliseconds:
export const options = {
thresholds: {
http_req_duration: [
{
threshold: 'p(99)<300',
abortOnFail: true,
},
],
},
};The threshold evaluates the aggregate request-duration distribution. If the condition fails, abortOnFail tells k6 to stop the workload when the violation is detected.
An error-rate threshold can also protect a test from continuing after too many requests fail:
thresholds: {
http_req_failed: [
{
threshold: 'rate<0.01',
abortOnFail: true,
},
],
}This example requires the request failure rate to remain below one percent. It is a useful performance guard, although the exercise's grading test checks for the required threshold names, p99 condition and abortOnFail configuration rather than requiring this particular error-rate expression.
Thresholds and checks serve different purposes.
Checks evaluate individual responses. You use them to verify that the restaurant list returned HTTP 200 or that a new order returned HTTP 201.
Thresholds evaluate aggregate metrics. They tell you whether the overall request failure rate or latency distribution meets a performance requirement.
A script can pass its individual checks while failing a performance threshold. For example, every request might return HTTP 200, but p99 could exceed 300 milliseconds.
The reverse distinction also matters. A good latency threshold does not prove that the correct endpoint response was received. You need both kinds of validation.
Reading the k6 summary
At the end of a run, k6 prints a summary containing the metrics collected during the workload.
The most useful metrics for this exercise include:
| Metric | What it tells you |
|---|---|
http_req_duration | Request latency distribution |
http_req_failed | Proportion of failed HTTP requests |
checks | Number and percentage of successful checks |
http_reqs | Total HTTP requests and achieved request rate |
The http_req_duration metric contains the median and percentile values. The http_req_failed metric tells you whether the workload experienced failed requests.
You should preserve this output rather than relying on terminal history.
Use --summary-export to write the summary as JSON:
k6 run \
--summary-export=loadtest/before-browse.json \
loadtest/browse.jsThe exported file preserves the measured results for later inspection and comparison.
The exercise saves two files:
backend/loadtest/before-browse.json
backend/loadtest/before-order.jsonFor each workload, record the median (med), p95, p99 and error rate. The summary should contain positive latency values for med, p(95) and p(99), along with the http_req_failed metric.
These files are the before numbers. Preserve them before changing the backend implementation.
Reproducible measurements
A performance measurement is useful only when you understand the conditions under which it was collected.
Your local environment runs several components at once:
- Go API and worker.
- MySQL.
- Redis.
- Redpanda.
- k6 as the load generator.
All these processes compete for machine resources. If k6 consumes most of the available CPU, the measured latency may reflect a saturated load generator rather than a slow API.
Record the processor, available CPU cores, RAM and machine used for the measurement. Hardware context makes comparisons more useful.
Warm the application before recording the baseline. Database connections may need to be established, and the menu cache may need to be populated. Cold-start effects can distort the results.
Change one thing at a time when investigating performance. Keep the original scripts, workload configuration and machine consistent between before and after runs.
The capacity estimation work later in the module uses measured throughput and latency to reason about what the backend can sustain. A local load test provides evidence about your setup, not a production capacity guarantee.
Common measurement failures
Several mistakes can make a load test produce misleading results.
Using VUs as a substitute for arrival rate
A closed workload with 100 VUs does not guarantee 100 incoming requests per second. Slow responses reduce the rate because each VU waits for its current iteration.
Use an open arrival-rate workload when you need to maintain a target incoming order rate.
Reusing an idempotency key
Repeated order submissions may return the previously recorded result rather than create new orders. Your checks may report HTTP 200 where the test expects HTTP 201.
Generate a unique key for every order iteration.
Sharing one identity across VUs
When all VUs use the same X-User-ID, the rate limiter can treat them as one caller. The resulting 429 responses can make the backend appear unable to handle a workload that was actually constrained by the test identities.
Assign each VU a distinct identity.
Ignoring response checks
A fast HTTP 401 or 400 response does not indicate that the order API is performing well. It indicates that the request failed to exercise the intended operation.
Verify status codes before interpreting latency.
Trusting the average alone
A low average can coexist with a high p99. Slow requests may affect a small number of customers while remaining almost invisible in the average.
Compare the median, p95 and p99 together.
Ignoring the load generator
An open workload needs enough VUs to execute scheduled iterations. If the generator runs out of available workers or CPU, it may fail to maintain the configured arrival rate.
Check the actual achieved request rate and monitor machine resources before blaming the API.
Before-number workload design
The exercise "Browse and order k6 scripts" applies these models to the existing API.
The browse workload uses a fixed number of VUs. Each iteration requests the restaurant list, selects a restaurant and requests its menu. Its defaults represent 300 VUs running for three minutes.
The order workload uses ramping-arrival-rate. It targets 100 order iterations per second after the ramp and holds that rate. Setup creates an authenticated customer and discovers a usable menu item before the measured iterations begin.
Both scripts include p99 in their summary statistics. They also use distinct VU identities where needed to avoid sharing a rate-limit bucket.
The two saved summaries preserve the measurements before the implementation changes.
In the next exercise, "Find and fix the first bottleneck", you will investigate the measurements using profiling and MySQL query plans. Keep the original workload unchanged so you can determine whether a change actually improves the measured results.
Check your understanding
You run a closed k6 workload with 20 VUs. Each iteration takes two seconds on average. Ignoring scheduling overhead, approximately how many iterations per second can the workload generate?
References
Everything above is explained on this page; these are where it comes from (k6).