Load testing an ASP.NET Core API with k6
ASP.NET Core APIs often look quick on a developer laptop, yet behave differently when hundreds of customers search, order, or authenticate at once. A load test exposes contention, slow dependencies, and capacity limits before customers find them during a busy trading period.
Load testing an ASP.NET Core API with k6 combines a JavaScript workload, repeatable request rates, and useful latency thresholds. It suits teams already shipping through Azure DevOps, GitHub Actions, or another CI/CD pipeline because the same scenario can run locally and in every build.
Success depends on choosing meaningful endpoints and test data, not simply pushing the largest possible number of requests. The useful evidence is a baseline: throughput, response-time percentiles, error rates, and the point where service levels begin to break.
For Australian teams, traffic shape, cloud regions, and privacy obligations need to shape the scenario. This guide covers a practical k6 setup while keeping the workload realistic for an organisation operating across Sydney, Melbourne, and the rest of the country.
Define the performance target
Start with an agreed service-level objective: for example, 95% of order lookups under 500 ms while fewer than 1% fail at the planned peak request rate. A specialist performance assessment can help separate useful thresholds from arbitrary numbers.
Choose a small set of business-critical endpoints and define what each request represents. An order search, catalogue query, and login request consume different amounts of application, database, and cache capacity. Record the expected request rate, acceptable response time, and permitted error rate for each journey.
| Consideration | k6 | Apache JMeter | Visual Studio load testing |
|---|---|---|---|
| Primary style | Code-first JavaScript | GUI-led and scriptable | Integrated test projects |
| Learning curve | Small for CI/CD scripts | Moderate | Familiar to .NET teams |
| Protocol support | HTTP, WebSockets and extensions | Broad plug-in ecosystem | Strong HTTP and Microsoft integrations |
| Distributed execution | Cloud or Kubernetes-based execution | Distributed JMeter engines | Microsoft-managed test agents |
| Best fit | Repeatable API checks in CI/CD | Complex mixed-protocol suites | Enterprises standardised on Visual Studio |
k6 is usually the most natural choice for a scripted API workload that must fit into an automated delivery pipeline. JMeter remains valuable for plug-in-heavy or mixed-protocol testing, while Visual Studio load testing can suit organisations with an established Microsoft test estate.
Model Australian traffic patterns
Australian business traffic commonly follows Sydney and Melbourne working hours rather than remaining flat throughout the day. Demand can rise during the eastern states morning rush, soften around arvo, and climb again as people leave work. Schedule ramp-up stages using AEST and AEDT so daylight-saving changes do not silently alter the test.
Retail workloads require special attention during national promotions such as Click Frenzy and Black Friday. Sale events concentrate traffic into short windows, favour cached catalogue pages over checkout calls, and can produce sudden bursts that exceed a gradual ramp. Model both the burst and the quieter periods that follow.
A national audience also introduces geographic variation. Users in Brisbane, Adelaide, and Perth may have different network latency from an API hosted in Sydney or Melbourne, especially when requests traverse multiple cloud services. Use distributed load-generation locations when the objective includes user experience across Australia rather than application capacity alone.
Prepare the API for a credible test
Match the test environment closely to production. Use the same .NET version, authentication flow, database shape, caching configuration, autoscaling rules, and application logging where possible. Many Australian Microsoft teams run .NET workloads on Azure App Service or Kubernetes with Microsoft Entra ID, so those dependencies should behave as they do in production.
The API must expose enough telemetry to explain a failure. Correlate k6 results with ASP.NET Core request logs, CPU and memory metrics, garbage collection, database timings, and external API calls. Keep the load generator outside the application resource boundary, since colocating it with the API can distort results and hide saturation.
Use synthetic customer records and test-only accounts. Under the Australian Privacy Act and Notifiable Data Breaches scheme, request payloads, headers, and application logs can still contain personal information. Store tokens as CI/CD secrets, redact captured responses, and restrict the target endpoint so an accidental run cannot affect live customers.
Build the k6 workload
Write the scenario in JavaScript and keep request-building logic separate from thresholds. The following example models rising traffic against a protected orders endpoint. BASE_URL and API_TOKEN come from the execution environment rather than being committed to the script.
import http from 'k6/http';
import { check, sleep } from 'k6';
import { Rate } from 'k6/metrics';
const applicationErrors = new Rate('application_errors');
export const options = {
scenarios: {
orders: {
executor: 'ramping-arrival-rate',
startRate: 20,
timeUnit: '1s',
preAllocatedVUs: 30,
maxVUsers: 150,
stages: [
{ target: 50, duration: '2m' },
{ target: 150, duration: '5m' },
{ target: 0, duration: '1m' }
],
gracefulStop: '30s'
}
},
thresholds: {
http_req_duration: ['p(95)<500', 'p(99)<1000'],
http_req_failed: ['rate<0.01'],
checks: ['rate>0.99'],
application_errors: ['rate<0.01']
}
};
const baseUrl = __ENV.BASE_URL;
const token = __ENV.API_TOKEN;
if (!baseUrl) {
throw new Error('BASE_URL is required');
}
export default function () {
const response = http.get(`${baseUrl}/api/orders`, {
headers: {
Accept: 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {})
}
});
applicationErrors.add(response.status >= 400);
check(response, {
'returns HTTP 200': r => r.status === 200,
'returns a response body': r => r.body.length > 0
});
sleep(0.2);
}
The arrival-rate executor models requests per second, while virtual users handle concurrent work and think time. Replace the sample thresholds and request rate with agreed service targets before using the script as a release gate. Running k6 run load-test.js with the environment configured produces the baseline and threshold results.
Run and interpret the results
Use a controlled sequence of tests: a short smoke run, a realistic peak workload, a stress run that pushes beyond expected demand, and a soak test for memory or connection leaks. Keep test data and server configuration consistent so changes in results point to application behaviour rather than a different scenario.
Focus on p95 and p99 latency, request throughput, error rate, and dropped iterations. An acceptable average can conceal a slow minority, while a rising count of dropped iterations shows that virtual users cannot generate the requested load. Compare each run with the previous baseline and investigate abrupt changes rather than relying on one isolated execution.
When performance falls, inspect the ASP.NET Core service before changing k6 settings. CPU saturation, thread-pool starvation, garbage collection pauses, exhausted Entity Framework connection pools, slow SQL queries, and time-consuming third-party calls can all increase response times. Apply the same timestamp to k6 metrics, traces, and infrastructure dashboards so the bottleneck can be identified quickly.
Keep tests repeatable and secure
Store the k6 script in source control with the application and review changes to scenarios, thresholds, and test data. Run it in CI/CD using tagged pipelines and retain JSON output as a build artifact. Stable configuration and historical results make regressions visible even when the team changes frameworks or hosting services.
Apply the same access controls used for other testing tools. Limit requests to approved non-production environments, cap the maximum load, and require an explicit target parameter. Avoid personal information in response bodies, distributed tracing attributes, and performance reports, even when the underlying API normally returns customer data.
For broader guidance on continuous testing, DevOps quality, and performance engineering, the quality articles collection provides useful context. k6 can also publish metrics to Prometheus for Grafana dashboards, making long-term trends visible without exposing sensitive payloads.
Turn results into release decisions
Translate the evidence into engineering work. A p99 breach caused by database connection contention becomes a pooling or query task; excessive garbage collection becomes an allocation investigation; missing autoscaling capacity becomes an infrastructure requirement. Attach the baseline, workload, findings, and agreed thresholds to the delivery backlog.
nFocus Software Testing can help Australian organisations assess API performance, implement Microsoft tooling, establish automated test coverage, and train teams in k6 and continuous testing. Book a load-testing assessment and leave your team with a repeatable workload, agreed service targets, and an evidence-based release decision.